
package com.joysuch.wwyt.dataimport.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joysuch.wwyt.api.basedata.service.BpDepartSyncService;
import com.joysuch.wwyt.api.basedata.service.BpJobSyncService;
import com.joysuch.wwyt.api.dataaccess.OrientationDataSyncService;
import com.joysuch.wwyt.api.dataaccess.bean.OrientationSearchBean;
import com.joysuch.wwyt.bp.bean.BpSafeTableExcelReturnBean;
import com.joysuch.wwyt.bp.bean.investigate.BpInvestigateStoreExcelBean;
import com.joysuch.wwyt.bp.bean.investigate.BpSafeTableExcelBean;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateStore;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateStoreDetail;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.enums.DepartType;
import com.joysuch.wwyt.bp.enums.DeviceFacilityTypes;
import com.joysuch.wwyt.bp.enums.RiskPointTypes;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.bp.service.BpEnterpriseInfoService;
import com.joysuch.wwyt.bp.service.BpStorageTankAreaService;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.common.entity.CommonType;
import com.joysuch.wwyt.common.enums.CommonTypes;
import com.joysuch.wwyt.common.repository.CommonTypeDao;
import com.joysuch.wwyt.common.service.CommonTypeService;
import com.joysuch.wwyt.core.bean.BaseNfcCardBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.entity.*;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.LoginUserStates;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.repository.*;
import com.joysuch.wwyt.core.service.*;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dataimport.bean.*;
import com.joysuch.wwyt.dataimport.service.DataImportService;
import com.joysuch.wwyt.dataimport.service.DataImportValidator;
import com.joysuch.wwyt.dataimport.util.ObjectStringUtils;
import com.joysuch.wwyt.dzhapi.bean.ApiBaseTypeGroupItemBean;
import com.joysuch.wwyt.dzhapi.mapper.ApiBaseTypeGroupItemMapper;
import com.joysuch.wwyt.edu.bean.WwytUedCertificateImportBean;
import com.joysuch.wwyt.edu.entity.EduQuestion;
import com.joysuch.wwyt.edu.entity.EduQuestionItem;
import com.joysuch.wwyt.edu.entity.WwytEduCertificate;
import com.joysuch.wwyt.edu.entity.WwytEduCertificateUser;
import com.joysuch.wwyt.edu.mapper.WwytEduCertificateUserMapper;
import com.joysuch.wwyt.edu.repository.EduQuestionDao;
import com.joysuch.wwyt.edu.repository.EduQuestionItemDao;
import com.joysuch.wwyt.edu.service.WwytEduCertificateService;
import com.joysuch.wwyt.edu.service.WwytEduCertificateUserService;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.entity.*;
import com.joysuch.wwyt.mh.repository.*;
import com.joysuch.wwyt.mh.service.MhMajorHazardService;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import com.joysuch.wwyt.monitoringcenter.bean.SyncBatchDataReturnBean;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.patrol.entity.PatrolDataType;
import com.joysuch.wwyt.patrol.entity.PatrolOption;
import com.joysuch.wwyt.patrol.entity.bean.PatrolCheckPointItemDetailBean;
import com.joysuch.wwyt.patrol.entity.bean.SimpleListDataType;
import com.joysuch.wwyt.patrol.entity.vo.CheckItemDetailVo;
import com.joysuch.wwyt.patrol.entity.vo.CheckItemVo;
import com.joysuch.wwyt.patrol.enums.DataTypeEnum;
import com.joysuch.wwyt.patrol.mapper.PatrolDataTypeMapper;
import com.joysuch.wwyt.patrol.mapper.PatrolOptionMapper;
import com.joysuch.wwyt.patrol.service.PatrolCheckPointService;
import com.joysuch.wwyt.risk.bean.RiskJhaEvaluationBean;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.RiskDistrictEvaluation;
import com.joysuch.wwyt.risk.entity.RiskPoint;
import com.joysuch.wwyt.risk.entity.RiskPointEvaluationJhaItem;
import com.joysuch.wwyt.risk.enums.ControlLevels;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.service.RiskDistrictEvaluationService;
import com.joysuch.wwyt.risk.service.RiskDistrictService;
import com.joysuch.wwyt.risk.service.RiskEvaluationExcelImportService;
import com.joysuch.wwyt.risk.service.RiskPointService;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import com.joysuch.wwyt.util.StringUtil;
import com.joysuch.wwyt.util.Validators;
import com.joysuch.wwyt.workflow.service.WorkFlowProcessService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class DataImportServiceImpl implements DataImportService {

    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BaseLoginAccountService baseLoginAccountService;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    private BpStorageTankAreaService storageTankAreaService;
    @Autowired
    private MhMajorHazardDao mhMajorHazardDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BaseRoleDao baseRoleDao;
    @Autowired
    private BpEnterpriseInfoDao bpEnterpriseInfoDao;
    @Autowired
    private MhMajorHazardChemProductDao mhMajorHazardChemProductDao;
    @Autowired
    private MhMajorHazardChemProductRelDao mhMajorHazardChemProductRelDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private BpIndustrialPipelineDao bpIndustrialPipelineDao;
    @Autowired
    private BpProductionFacilityTypeDao bpProductionFacilityTypeDao;
    @Autowired
    private BpMonitoringPointRelDao bpMonitoringPointRelDao;
    @Autowired
    private BaseTypeGroupDao baseTypeGroupDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;
    @Autowired
    private MhMonitoringPointDao monitoringPointDao;
    @Autowired
    private MhMonitoringTypeDao monitoringTypeDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private RiskDistrictEvaluationService riskDistrictEvaluationService;
    @Autowired
    private BpDeviceFacilityCollectionService deviceFacilityCollectionService;
    @Autowired
    private BPNFCLocationDao bpnfcLocationDao;
    @Autowired
    private CommonTypeDao commonTypeDao;
    @Autowired
    private CommonTypeService commonTypeService;
    @Autowired
    private EduQuestionDao eduQuestionDao;
    @Autowired
    private EduQuestionItemDao eduQuestionItemDao;

    @Autowired
    private BaseRoleUserLoginRoleDao baseRoleUserLoginRoleDao;
    @Autowired
    private RiskDistrictService riskDistrictService;
    @Autowired
    private BpSystemVideoDao bpSystemVideoDao;
    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;
    @Autowired
    private BpEnterpriseInfoService bpEnterpriseInfoService;
    @Autowired
    private BpInvestigateStoreDetailRepository detailRepository;
    @Autowired
    private BpInvestigateStoreRepository storeRepository;
    @Autowired
    private WwytEduCertificateService wwytEduCertificateService;
    @Autowired
    private WwytEduCertificateUserService wwytEduCertificateUserService;
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    @Autowired
    private BaseRoleDataAuthService dataAuthService;
    @Autowired
    private WorkFlowProcessService workFlowProcessService;
    @Autowired
    private MhMajorHazardService mhMajorHazardService;
    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private BpContractorDao bpContractorDao;
    @Autowired
    private WwytEduCertificateUserMapper wwytEduCertificateUserMapper;
    @Autowired
    private LocateServerService locateServerService;
    @Autowired
    private BpDepartSyncService departSyncService;
    @Autowired
    private BpJobSyncService jobSyncService;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private BpStorageTankAreaDao bpStorageTankAreaDao;
    @Autowired
    private BpStorageTankDao bpStorageTankDao;
    @Autowired
    private BpDeviceFacilityCollectionService bpDeviceFacilityCollectionService;
    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private OrientationDataSyncService orientationDataSyncService;
    @Autowired
    private BpDeviceFacilityCollectionDao bpDeviceFacilityCollectionDao;
    @Autowired
    private PatrolDataTypeMapper patrolDataTypeMapper;
    @Autowired
    private PatrolOptionMapper patrolOptionMapper;
    @Autowired
    private PatrolCheckPointService patrolCheckPointService;
    @Autowired
    private RiskEvaluationExcelImportService riskEvaluationExcelImportService;

    @Autowired
    private ApiBaseTypeGroupItemMapper itemMapper;

    @Override
    public int batchAddLoginAccountForNoAccountUsers(String[] excludeUserCodes, String defaultPassword) {
        List<BaseUser> users = baseUserService.findAllNoLoginAccountUsers(excludeUserCodes);
        for (BaseUser u : users) {
            baseLoginAccountService.createLoginAccountIfNotExists(u, u.getCode(), defaultPassword);
        }
        return users.size();
    }

    /**
     * 导入储罐、储罐区
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importBpStoreTankAndArea(MultipartFile file) {
        List<StoreTankAreaBean> areas = parseData(file, 0, StoreTankAreaBean.class, true);
        List<StoreTankBean> tanks = parseData(file, 1, StoreTankBean.class, true);
        List<BpDepart> deptList = getOwnedAuthDeptCodeMapping();
        Map<String, Long> departCountMap = this.getDepartCountMap(deptList);
        Map<String, BpDepart> nameDeptMap = this.getNameDeptMap(deptList);
        int count1 = 0;
        int count2 = 0;
        int error1 = 0;
        int error2 = 0;
        int ignore1 = 0;
        int ignore2 = 0;
        List<String> errors = new ArrayList<>();
        Map<String, MhMajorHazard> hazardCodeMap = this.getHazardCodeMap();
        Map<String, Long> pointCodeMap = this.getPointCodeMap();
        // 储罐区导入
        for (int i = 0; i < areas.size(); i++) {
            StoreTankAreaBean area = areas.get(i);
            if (area == null) {
                continue;
            }
            String areaCode = area.getCode();
            String areaName = area.getName();
            if (StringUtils.isBlank(areaCode)) {
                errors.add(String.format("储罐区第{%s}行:储罐区编号不能为空", areas.get(i).getRowIndex()));
                error1++;
                continue;
            } else if (StringUtils.isBlank(areaName)) {
                errors.add(String.format("储罐区第{%s}行:储罐区名称不能为空", areas.get(i).getRowIndex()));
                error1++;
                continue;
            }
            final String responsibleDeptParentName = areas.get(i).getResponsibleDeptParentName();
            final String responsibleDeptName = areas.get(i).getResponsibleDeptName();
            String errorMsg = this.checkDataAuth(responsibleDeptParentName, responsibleDeptName, nameDeptMap, departCountMap);
            if (!StringUtils.isBlank(errorMsg)) {
                errors.add(String.format(errorMsg, "储罐区", areas.get(i).getRowIndex()));
                error1++;
                continue;
            }
            try {
                if (StringUtils.isNotBlank(areas.get(i).getMajorHazardCode())) {
                    if (!hazardCodeMap.containsKey(areas.get(i).getMajorHazardCode())) {
                        errors.add(String.format("储罐区第{%s}行:该重大危险源不在权限范围内", areas.get(i).getRowIndex()));
                    }
                }
                String mpc = areas.get(i).getMinitorPointCodes();
                if (StringUtils.isNotBlank(mpc)) {
                    if (this.getPointCodeFlag(mpc, pointCodeMap)) {
                        errors.add(String.format("储罐区第{%s}行:存在监测点不在权限范围内", areas.get(i).getRowIndex()));
                    }
                }
                Long responsibleDeptId;
                if (departCountMap.get(responsibleDeptName) > 1) {
                    responsibleDeptId = findDeptIdByParentDeptName(deptList, responsibleDeptName, responsibleDeptParentName);
                    if (responsibleDeptId == null) {
                        error1++;
                        errors.add(String.format("储罐区第{%s}行:部门存在多个且直属上级部门未找到", areas.get(i).getRowIndex()));
                        continue;
                    }
                } else {
                    responsibleDeptId = nameDeptMap.get(responsibleDeptName).getId();
                }
                Integer rsDeptId = responsibleDeptId == null ? null : responsibleDeptId.intValue();

                //保存
                BpStorageTankArea tankArea = new BpStorageTankArea();
                if (storageTankAreaService.findByCode(area.getCode()) != null) {
                    tankArea = storageTankAreaService.findByCode(area.getCode());
                }
                translateHasChineseToYesNo(area);
                BeanUtils.copyProperties(area, tankArea);
                MhMajorHazard mh = mhMajorHazardDao.findByCode(area.getMajorHazardCode());
                if (mh != null) {
                    tankArea.setMhMajorHazard(mh);
                }
//                if (StringUtils.isBlank(tankArea.getCode())) {
//                    tankArea.setCode(bizCodeGeneratorFacade.chuGuanQu());
//                }
                tankArea.setResponsibleDept(rsDeptId == null ? null : rsDeptId.longValue());
                tankArea = bpStorageTankAreaDao.save(tankArea);
//         保存监测点信息
                List<Long> pointIds = this.getStorePointIds(area.getMinitorPointCodes(), pointCodeMap);
                bpMonitoringPointRelDao.deleteByRefTypeAndRefId("store_tank_area", tankArea.getId());
                for (Long pointId : pointIds) {
                    String checkResult = mhMonitoringPointService.checkMhMointPoint(pointId, tankArea.getId());
                    if (StringUtils.isNotBlank(checkResult)) {
                        errors.add(String.format("储罐区第{%s}行:" + checkResult, area.getRowIndex()));
                        continue;
                    } else {
                        BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                        bpMonitoringPointRel.setRefType("store_tank_area");
                        bpMonitoringPointRel.setRefId(tankArea.getId());
                        bpMonitoringPointRel.setMonitoringPointId(pointId);
                        bpMonitoringPointRelDao.save(bpMonitoringPointRel);
                    }
                }
                //将生产装置录入生产装置总表
                BpDeviceFacilityCollection tankAreaCollection = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(DeviceFacilityTypes.CHU_GUAN_QU, tankArea.getId(), tankArea.getCode(), tankArea.getName(), null, tankArea.getMhMajorHazard() == null ? null : tankArea.getMhMajorHazard().getId(), tankArea.getLocation());
                // 绑定监测点
                bpDeviceFacilityCollectionService.bindDeviceAndMonitorPointsByIds(tankAreaCollection, pointIds);
                count1++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("储罐区第{%s}行:数据过长", areas.get(i).getRowIndex()));
                error1++;
                log.error(e.getMessage(), e);
                continue;
            } catch (Exception e) {
                errors.add(String.format("储罐区第{%s}行:数据异常", areas.get(i).getRowIndex()));
                error1++;
                log.error(e.getMessage(), e);
                continue;
            }
        }

        if (!CollectionUtils.isEmpty(tanks)) {
            // 储罐导入
            for (int i = 0; i < tanks.size(); i++) {
                StoreTankBean tank = tanks.get(i);
                if (StringUtils.isBlank(tank.getUniCode())) {
                    errors.add(String.format("储罐第{%s}行:储罐编号不能为空", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                } else if (StringUtils.isBlank(tank.getName())) {
                    errors.add(String.format("储罐第{%s}行:储罐名称不能为空", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                } else if (StringUtils.isBlank(tank.getBelongGroupCode())) {
                    errors.add(String.format("储罐第{%s}行:所属储罐区编码不能为空", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                } else if (StringUtils.isBlank(tank.getType())) {
                    errors.add(String.format("储罐第{%s}行:储罐形式不能为空", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                }

                // 根据灌区编码查询灌区名称
                String areaCode = tank.getBelongGroupCode();
                BpStorageTankArea area = storageTankAreaService.findByCode(areaCode);
                if (area == null) {
                    errors.add(String.format("储罐第{%s}行:该储罐区不存在", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                }

                List<Long> deptIds = dataAuthService.findDepartIdsByCurUser();
                if (!deptIds.contains(Long.valueOf(area.getResponsibleDept()))) {
                    errors.add(String.format("储罐第{%s}行:无权限导入该储罐区数据", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                }

                if (StringUtils.isNotBlank(tanks.get(i).getMajorHazardCode())) {
                    if (!hazardCodeMap.containsKey(tanks.get(i).getMajorHazardCode())) {
                        errors.add(String.format("储罐第{%s}行:该重大危险源不在权限范围内", tanks.get(i).getRowIndex()));
                    }
                }
                String mpc = tanks.get(i).getMinitorPointCodes();
                if (StringUtils.isNotBlank(mpc)) {
                    if (this.getPointCodeFlag(mpc, pointCodeMap)) {
                        errors.add(String.format("储罐第{%s}行:存在监测点不在权限范围内", tanks.get(i).getRowIndex()));
                    }
                }

                if (tank.getWorkPressureHighValue() != null && tank.getWorkPressureLowValue() != null && tank.getWorkPressureHighValue() < tank.getWorkPressureLowValue()) {
                    errors.add(String.format("储罐第{%s}行:工作压力区间数值填写不正确", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                }
                if (tank.getWorkTemperatureHighValue() != null && tank.getWorkTemperatureLowValue() != null && tank.getWorkTemperatureHighValue() < tank.getWorkTemperatureLowValue()) {
                    errors.add(String.format("储罐第{%s}行:工作温度区间数值填写不正确", tanks.get(i).getRowIndex()));
                    error2++;
                    continue;
                }

                tank.setBelongGroupName(area.getName());
                try {
                    translateHasChineseToYesNo(tank);
                    BpStorageTank t = new BpStorageTank();
                    if (bpStorageTankDao.findByUniCode(tank.getUniCode()) != null) {
                        t = bpStorageTankDao.findByUniCode(tank.getUniCode());
                    }
                    BeanUtils.copyProperties(tank, t);
                    //由于之前储罐code和uniCode在新增时可能不一致,现将code与unicode值进行统一
                    t.setCode(tank.getUniCode());
                    //投用日期
                    if (StringUtils.isNotBlank(tank.getCommissioningDate())) {
                        t.setCommissioningDate(DateUtil.parse(tank.getCommissioningDate()));
                    } else {
                        t.setCommissioningDate(null);
                    }
                    MhMajorHazard mh = mhMajorHazardDao.findByCode(tank.getMajorHazardCode());
                    if (mh != null) {
                        t.setMhMajorHazard(mh);
                    }
                    t.setBpStorageTankArea(area.getId());
                    t = bpStorageTankDao.save(t);
//         保存监测点信息
                    List<Long> pointIds = this.getStorePointIds(tank.getMinitorPointCodes(), pointCodeMap);
                    bpMonitoringPointRelDao.deleteByRefTypeAndRefId("store_tank", t.getId());
                    for (Long pointId : pointIds) {
                        String checkResult = mhMonitoringPointService.checkMhMointPoint(pointId, t.getId());
                        if (StringUtils.isNotBlank(checkResult)) {
                            errors.add(String.format("储罐第{%s}行:" + checkResult, tank.getRowIndex()));
                            continue;
                        } else {
                            BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                            bpMonitoringPointRel.setRefType("store_tank");
                            bpMonitoringPointRel.setRefId(t.getId());
                            bpMonitoringPointRel.setMonitoringPointId(pointId);
                            bpMonitoringPointRelDao.save(bpMonitoringPointRel);
                        }
                    }
                    //将生产装置录入生产装置总表
                    BpDeviceFacilityCollection tankCollection = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(DeviceFacilityTypes.CHU_GUAN, t.getId(), t.getCode(), t.getName(), null, t.getMhMajorHazard() == null ? null : t.getMhMajorHazard().getId(), t.getLocation());
                    // 绑定监测点
                    bpDeviceFacilityCollectionService.bindDeviceAndMonitorPointsByIds(tankCollection, pointIds);
                    count2++;
                } catch (DataIntegrityViolationException e) {
                    errors.add(String.format("储罐第{%s}行:数据过长", tanks.get(i).getRowIndex()));
                    error2++;
                    log.error(e.getMessage(), e);
                } catch (Exception e) {
                    errors.add(String.format("储罐第{%s}行:数据异常", tanks.get(i).getRowIndex()));
                    error2++;
                    log.error(e.getMessage(), e);
                }
            }
        }

        // 返回前端,对list进行处理
        List returnList = new ArrayList<>();
        returnList.add(String.format("储罐区: 成功导入%s条; 失败%s条,忽略 %s 条; 储罐: 成功导入%s条; 失败%s条,忽略 %s 条;", count1, error1,
                ignore1, count2, error2, ignore2));
        for (int i = 0; i < errors.size(); i++) {
            returnList.add(errors.get(i));
        }
        return returnList;
    }

    /**
     * 岗位导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importJobByExcel(MultipartFile file) {
        List<ExcelJobBean> jobs = parseData(file, 0, ExcelJobBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        boolean sync = baseConfigService.checkIfSync();
        for (int i = 0; i < jobs.size(); i++) {
            ExcelJobBean jBean = jobs.get(i);
            if (StringUtils.isBlank(jBean.getName())) {
                errors.add(String.format("岗位第{%s}行:岗位不能为空", jBean.getRowIndex()));
                error++;
                continue;
            } else if (null != bpJobDao.findByName(jBean.getName())) {
                errors.add(String.format(String.format("岗位第{%s}行:岗位已存在", jBean.getRowIndex())));
                ignore++;
                continue;
            }
            try {
                BpJob bpJob = new BpJob();
                if (bpJobDao.findByName(jBean.getName()) != null) {
                    bpJob = bpJobDao.findByName(jBean.getName());
                }
                BeanUtils.copyProperties(jBean, bpJob);
                if (bpJob.getUniqueId() == null) {
                    bpJob.setUniqueId(SnowFlakeUtil.getJobId());
                    bpJob.setLocateSync(false);
                }
                List<RiskDistrict> districtList = riskDistrictDao.findByCode(jBean.getRiskDistrictCode());
                if (StringUtils.isNotBlank(jBean.getRiskDistrictCode())) {
                    if (CollectionUtils.isEmpty(districtList)) {
                        errors.add(String.format("岗位第{%s}行:风险分区不存在", jBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    bpJob.setRiskDistrictId(districtList.get(0).getId());
                    bpJob.setRiskDistrictName(districtList.get(0).getName());
                }
                bpJob.setName(jBean.getName());
                bpJob.setStaffCount(0);
                bpJobDao.save(bpJob);
                if (sync) {
                    boolean b = jobSyncService.syncjob(bpJob);
                    bpJob.setLocateSync(b);
                    bpJobDao.save(bpJob);
                    if (!b) {
                        errors.add(String.format("岗位第{%s}行:岗位同步失败", jBean.getRowIndex()));
                        error++;
                        continue;
                    }
                }
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("岗位第{%s}行:数据过长", jBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("岗位第{%s}行:数据异常", jBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "岗位");
    }

    /**
     * 部门导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importDepartByExcel(MultipartFile file) {
        List<ExcelDepartBean> departs = parseData(file, 0, ExcelDepartBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        boolean sync = baseConfigService.checkIfSync();
        //同步顶级部门
        if (sync) {
            List<BpDepart> parents = bpDepartDao.findByLocateSyncAndParentIsNull();
            if (!CollectionUtils.isEmpty(parents)) {
                BpDepart bd = parents.get(0);
                if (bd.getUniqueId() == null) {
                    bd.setUniqueId(SnowFlakeUtil.getDepartId());
                }
                boolean b = departSyncService.updateSync(bd, null);
                if (b) {
                    bd.setLocateSync(true);
                    bpDepartDao.save(bd);
                } else {
                    return Lists.newArrayList("顶级部门同步失败,请检查名称和同步Id，uniqueId =" + bd.getUniqueId());
                }
            }
        }
        for (int i = 0; i < departs.size(); i++) {
            ExcelDepartBean dBean = departs.get(i);
            if (StringUtils.isBlank(dBean.getDepartName())) {
                errors.add(String.format("部门第{%s}条:部门名称不能为空", dBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(dBean.getParentDepartName())) {
                errors.add(String.format("部门第{%s}条:上级部门名称不能为空", dBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                Long pId = bpDepartDao.findIdByName(dBean.getParentDepartName());
                if (null == pId) {
                    errors.add(String.format("部门第{%s}条:上级部门不存在", dBean.getRowIndex()));
                    error++;
                    continue;
                }
                BpDepart parentDepart = bpDepartDao.findById(pId).get();
                BpDepart bpDepart = new BpDepart();
                if (StringUtils.isNotBlank(dBean.getDepartCode()) && bpDepartDao.findFirstByCode(dBean.getDepartCode()) != null) {
                    bpDepart = bpDepartDao.findFirstByCode(dBean.getDepartCode());
                    List<BpDepart> bpDepartList = bpDepartDao.findByNameAndParentIdAndIdNotEq(dBean.getDepartName(), pId, bpDepart.getId());
                    if (!CollectionUtils.isEmpty(bpDepartList)) {
                        errors.add(String.format("部门第{%s}行:部门名称已存在", dBean.getRowIndex()));
                        error++;
                        continue;
                    }

                    bpDepart.setName(dBean.getDepartName());
                    if (bpDepart.getUniqueId() == null) {
                        bpDepart.setLocateSync(false);
                        bpDepart.setUniqueId(SnowFlakeUtil.getDepartId());
                    }
                    bpDepartDao.save(bpDepart);
                    if (sync) {
                        boolean b = departSyncService.syncDepart(bpDepart, parentDepart);
                        if (!b) {
                            errors.add(String.format("部门第{%s}行:部门同步失败", dBean.getRowIndex()));
                            error++;
                            continue;
                        }
                        bpDepart.setLocateSync(b);
                        bpDepartDao.save(bpDepart);
                    }
                    count++;
                } else {
                    bpDepart.setName(dBean.getDepartName());
                    bpDepart.setUniqueId(SnowFlakeUtil.getDepartId());
                    bpDepart.setLocateSync(false);
                    bpDepart.setParentId(pId);
                    // 锁定父部门，防止并发修改，导致childNo出错
                    // entityManager.lock(parentDepart, LockModeType.PESSIMISTIC_WRITE);
                    Integer no = parentDepart.getChildNo();
                    if (no == null) {
                        no = 1;
                    }
                    bpDepart.setChildNo(1);
                    bpDepart.setType(DepartType.DEPART.getId());
                    bpDepart.setCode(parentDepart.getCode() + "-" + StringUtils.leftPad(no + "", 3, '0'));
                    List<BpDepart> bpDepartList = bpDepartDao.findByNameAndParentId(dBean.getDepartName(), pId);
                    if (!CollectionUtils.isEmpty(bpDepartList)) {
                        errors.add(String.format("部门第{%s}行:部门名称已存在", dBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    bpDepartDao.save(bpDepart);
                    int cc = bpDepartDao.countByCodeAndState(bpDepart.getCode());
                    if (cc > 1) {
                        errors.add(String.format("部门第{%s}行:部门编码已存在", dBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    parentDepart.setChildNo(no + 1);
                    if (parentDepart.getUniqueId() == null) {
                        parentDepart.setLocateSync(false);
                        parentDepart.setUniqueId(SnowFlakeUtil.getDepartId());
                    }
                    bpDepartDao.save(parentDepart);
                    if (sync) {
                        boolean b = departSyncService.syncDepart(bpDepart, parentDepart);
                        if (!b) {
                            errors.add(String.format("部门第{%s}行:部门同步失败", dBean.getRowIndex()));
                            error++;
                            continue;
                        }
                        bpDepart.setLocateSync(b);
                        bpDepartDao.save(bpDepart);
                    }
                    count++;
                }
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("部门第{%s}行:数据过长", dBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("部门第{%s}行:数据异常", dBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "部门");
    }


    /**
     * 人员导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importUserByExcel(MultipartFile file) {
        List<ExcelUserBean> users = parseData(file, 0, ExcelUserBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        // 身份
        Map<String, Long> roleMap = new HashMap<>();
        roleMap.put("员工", Long.valueOf(0));
        roleMap.put("管理人员", Long.valueOf(1));
        roleMap.put("企业负责人", Long.valueOf(2));
        // 公司
        Map<String, Long> companyMap = new HashMap<>();
        List<BpEnterpriseInfo> companyList = bpEnterpriseInfoDao.findAll();
        for (BpEnterpriseInfo company : companyList) {
            companyMap.put(company.getName(), company.getId());
        }
        // 部门
        Map<String, Long> departMap = new HashMap<>();
        List<BpDepart> departList = bpDepartDao.findAll();
        for (BpDepart depart : departList) {
            departMap.put(depart.getName(), depart.getId());
        }

        // 岗位
        Map<String, Long> jobMap = new HashMap<>();
        List<BpJob> jobList = bpJobDao.findAll();
        for (BpJob job : jobList) {
            jobMap.put(job.getName(), job.getId());
        }

        // 证件
        Map<String, Long> cardNameMap = new HashMap<>();
        cardNameMap.put("居民身份证", Long.valueOf(0));
        cardNameMap.put("士官证", Long.valueOf(1));
        cardNameMap.put("学生证", Long.valueOf(2));
        cardNameMap.put("驾驶证", Long.valueOf(3));
        cardNameMap.put("护照", Long.valueOf(4));
        cardNameMap.put("港澳通行证", Long.valueOf(5));
        // 健康状态
        Map<String, Long> healthMap = getGroutItemMap("健康状况");
        // 学历
        Map<String, Long> degreeMap = getGroutItemMap("学历");

        //获取人员定位开关importJobByExcel
        boolean syncOpen = baseConfigService.checkIfSync();
        long syncAccount = 0;
        List<BaseUser> userList = new ArrayList<>();
        Map<Long, BaseUser> syncMap = new LinkedHashMap();
        for (int i = 0; i < users.size(); i++) {
            ExcelUserBean uBean = users.get(i);
            if (StringUtils.isBlank(uBean.getCode())) {
                errors.add(String.format("人员第{%s}行:人员工号不能为空", uBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(uBean.getRealName())) {
                errors.add(String.format("人员第{%s}行:人员姓名不能为空", uBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(uBean.getRoleName())) {
                errors.add(String.format("人员第{%s}行:人员身份不能为空", uBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(uBean.getDepartName())) {
                errors.add(String.format("人员第{%s}行:人员部门不能为空", uBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(uBean.getJobName())) {
                errors.add(String.format("人员第{%s}行:人员岗位不能为空", uBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(uBean.getCompanyName())) {
                errors.add(String.format("人员第{%s}行:工作单位不能为空", uBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                List<BaseUser> userSns;
                List<BaseUser> userCards;
                List<BpContractorStaff> staffSns;
                List<BpContractorStaff> staffCards;
                if (StringUtils.isNotBlank(uBean.getSn())) {
                    if (!Validators.validateMac(uBean.getSn())) {
                        errors.add(String.format("人员第{%s}行:定位卡号格式不正确", uBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    staffSns = bpContractorStaffDao.findBySnAndState(uBean.getSn(), 1);
                    if (!CollectionUtils.isEmpty(staffSns)) {
                        errors.add(String.format("人员第{%s}行:定位卡号已被承包商人员使用", uBean.getRowIndex()));
                        error++;
                        continue;
                    }
                }
                if (StringUtils.isNotBlank(uBean.getCardNumber())) {
                    staffCards = bpContractorStaffDao.findByCardNumberAndState(uBean.getCardNumber(), 1);
                    if (!CollectionUtils.isEmpty(staffCards)) {
                        errors.add(String.format("人员第{%s}行:门禁卡号已被承包商人员使用", uBean.getRowIndex()));
                        error++;
                        continue;
                    }
                }
                BaseUser bUser = new BaseUser();
                boolean exist = false;
                if (baseUserDao.findByCode(uBean.getCode()) != null) {
                    bUser = baseUserDao.findByCode(uBean.getCode());
                    exist = true;
                    if (baseUserDao.countOfRealNameAndIdNotEq(uBean.getRealName(), bUser.getId()) > 0) {
                        errors.add(String.format("人员第{%s}行:人员姓名已存在请修改后重新导入", uBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    if (StringUtils.isNotBlank(uBean.getSn())) {
                        userSns = baseUserDao.findBySnAndIdNotEq(uBean.getSn(), bUser.getId());
                        if (!CollectionUtils.isEmpty(userSns)) {
                            errors.add(String.format("人员第{%s}行:定位卡号已被人员使用", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    } else {
                        if (bUser.isLocateSync() && StringUtils.isNotBlank(bUser.getSn()) && syncOpen) {
                            //解绑SN
                            locateServerService.labelUntie(bUser.getSn());
                        }
                    }
                    if (StringUtils.isNotBlank(uBean.getCardNumber())) {
                        userCards = baseUserDao.findByCardNumberAndIdNotEq(uBean.getCardNumber(), bUser.getId());
                        if (!CollectionUtils.isEmpty(userCards)) {
                            errors.add(String.format("人员第{%s}行:门禁卡号已人员使用", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(uBean.getAccount())) {
                        //忽略自己的账户
                        BaseLoginAccount bla = baseLoginAccountDao.findFirstByUserNameAndUserDetailIdNotEq(uBean.getAccount(), bUser.getId());
                        if (bla != null) {
                            errors.add(String.format("人员第{%s}行:账号已存在", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    if (null != uBean.getCapId()) {
                        BaseImageRepository imageByCapId = baseImageRespositoryDao.findImageByCapId(uBean.getCapId());
                        if (null == imageByCapId) {
                            errors.add(String.format("人员第{%s}行:图标不存在", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    //报警模板
                    if (StringUtils.isNotBlank(uBean.getAlarmTemplateName())) {
                        Integer alarmTemplateId = findAlarmTemplate(uBean.getAlarmTemplateName());
                        if (null == alarmTemplateId) {
                            errors.add(String.format("人员第{%s}行: 报警模板不存在,请检查确认", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                        bUser.setAlarmTemplateId(Long.valueOf(alarmTemplateId));
                    } else {
                        bUser.setAlarmTemplateId(null);
                        bUser.setAlarmTemplateName(null);
                    }
                } else {
                    if (baseUserDao.countOfRealName(uBean.getRealName()) > 0) {
                        errors.add(String.format("人员第{%s}行:人员姓名已存在请修改后重新导入", uBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    if (StringUtils.isNotBlank(uBean.getSn())) {
                        userSns = baseUserDao.findBySn(uBean.getSn());
                        if (!CollectionUtils.isEmpty(userSns)) {
                            errors.add(String.format("人员第{%s}行:定位卡号已被人员使用", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(uBean.getCardNumber())) {
                        userCards = baseUserDao.findByCardNumber(uBean.getCardNumber());
                        if (!CollectionUtils.isEmpty(userCards)) {
                            errors.add(String.format("人员第{%s}行:门禁卡号已被人员使用", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(uBean.getAccount())) {
                        BaseLoginAccount bla = baseLoginAccountDao.findFirstByUserName(uBean.getAccount());
                        if (bla != null) {
                            errors.add(String.format("人员第{%s}行:账号已存在", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    if (null != uBean.getCapId()) {
                        BaseImageRepository imageByCapId = baseImageRespositoryDao.findImageByCapId(uBean.getCapId());
                        if (null == imageByCapId) {
                            errors.add(String.format("人员第{%s}行:图标不存在", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                    //报警模板
                    if (StringUtils.isNotBlank(uBean.getAlarmTemplateName())) {
                        Integer alarmTemplateId = findAlarmTemplate(uBean.getAlarmTemplateName());
                        if (null == alarmTemplateId) {
                            errors.add(String.format("人员第{%s}行: 报警模板不存在,请检查确认", uBean.getRowIndex()));
                            error++;
                            continue;
                        }
                        bUser.setAlarmTemplateId(Long.valueOf(alarmTemplateId));
                    }
                }

                BeanUtils.copyProperties(uBean, bUser);
                if (StringUtils.isNotBlank(uBean.getPersonTypeName())) {
                    ApiBaseTypeGroupItemBean itemBean = itemMapper.findByName(uBean.getPersonTypeName(), Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                    if (itemBean != null) {
                        bUser.setPersonTypeId(itemBean.getId());
                    }
                }
//                bUser.setCode(uBean.getCode());
//                bUser.setRealName(uBean.getRealName());
                if (roleMap.containsKey(uBean.getRoleName())) {
                    bUser.setRole(roleMap.get(uBean.getRoleName()));
                } else {
                    log.error("人员第" + uBean.getRowIndex() + "行数据异常-身份不存在");
                    errors.add(String.format("人员第{%s}行:人员身份不存在", uBean.getRowIndex()));
                    error++;
                    continue;
                }

                if (companyMap.containsKey(uBean.getCompanyName())) {
                    bUser.setWorkCompanyId(companyMap.get(uBean.getCompanyName()));
                } else {
                    log.error("人员第" + uBean.getRowIndex() + "行数据异常-工作单位不存在");
                    errors.add(String.format("人员第{%s}行:工作单位不存在", uBean.getRowIndex()));
                    error++;
                    continue;
                }

                if (departMap.containsKey(uBean.getDepartName())) {
                    bUser.setDepartId(departMap.get(uBean.getDepartName()));
                } else {
                    log.error("人员第" + uBean.getRowIndex() + "行数据异常-部门不存在");
                    errors.add(String.format("人员第{%s}行:部门不存在", uBean.getRowIndex()));
                    error++;
                    continue;
                }

                if (jobMap.containsKey(uBean.getJobName())) {
                    bUser.setJob(jobMap.get(uBean.getJobName()));
                } else {
                    log.error("人员第" + uBean.getRowIndex() + "行数据异常-岗位不存在");
                    errors.add(String.format("人员第{%s}行:岗位不存在", uBean.getRowIndex()));
                    error++;
                    continue;
                }
//                bUser.setSn(uBean.getSn());
//                bUser.setCardNumber(uBean.getCardNumber());
//                bUser.setGender(uBean.getGender());
                BaseTypeGroup type = baseTypeGroupDao.findByName("民族");
                if (type == null) {
                    log.error("人员第" + uBean.getRowIndex() + "行数据异常-民族类型不存在,请在数据字典中配置民族");
                }
                if (StringUtils.isNotBlank(uBean.getNation())) {
                    Long nId = baseTypeGroupItemDao.findIdByName(uBean.getNation(), type.getId());
                    if (null == nId) {
                        log.error("人员第" + uBean.getRowIndex() + "行数据异常-民族不存在");
                    } else {
                        bUser.setNation(nId);
                    }
                } else {
                    bUser.setNation(null);
                }

                if (StringUtils.isNotBlank(uBean.getIdCardType())) {
                    if (cardNameMap.containsKey(uBean.getIdCardType())) {
                        bUser.setIdCardType(cardNameMap.get(uBean.getIdCardType()));
                    } else {
                        log.error("人员第" + uBean.getRowIndex() + "行数据异常-证件类型不存在");
                    }
                } else {
                    bUser.setIdCardType(null);
                }

//                bUser.setIdCardNo(uBean.getIdCardNo());
//                bUser.setTelephone(uBean.getTelephone());

                if (StringUtils.isNotBlank(uBean.getHealth())) {
                    if (healthMap.containsKey(uBean.getHealth())) {
                        bUser.setHealthStatus(healthMap.get(uBean.getHealth()));
                    } else {
                        log.error("人员第" + uBean.getRowIndex() + "行数据异常-健康状态不存在");
                    }
                } else {
                    bUser.setHealthStatus(null);
                }
                if (StringUtils.isNotBlank(uBean.getDegree())) {
                    if (degreeMap.containsKey(uBean.getDegree())) {
                        bUser.setEducation(degreeMap.get(uBean.getDegree()));
                    } else {
                        log.error("人员第" + uBean.getRowIndex() + "行数据异常-学历类型不存在");
                    }
                } else {
                    bUser.setEducation(null);
                }
//                bUser.setMajor(uBean.getMajor());
                bUser.setCensus(uBean.getCensusRegisterAddr());
//                bUser.setAddress(uBean.getAddress());
//                bUser.setPostcode(uBean.getPostcode());
                bUser.setJoinWorkDate(uBean.getAttendWorkTime());
//                bUser.setTitle(uBean.getTitle());
                bUser.setState(DataStateTypes.EFFECTIVE.getState());
                //邮箱
//                bUser.setEmail(uBean.getEmail());
                if (bUser.getUniqueId() == null) {
                    bUser.setUniqueId(SnowFlakeUtil.getUserId());
                }
                bUser.setLocateSync(false);
                //默认帽子图标
                if (bUser.getCapId() == null) {
                    bUser.setCapId(1L);
                }
                BaseUser save = baseUserDao.save(bUser);
                syncMap.put(save.getId(), save);
                if (!exist) {
                    userList.add(bUser);
                }
                //没有账号新增 并赋值初始密码 已有账号修改账号名称
                if (StringUtils.isNotBlank(uBean.getAccount())) {
                    BaseLoginAccount loginAccount = baseLoginAccountDao.findByUserDetailId(save.getId());
                    if (loginAccount == null) {
                        loginAccount = new BaseLoginAccount();
                        loginAccount.setBaseUser(save);
                        loginAccount.setUserName(uBean.getAccount());
                        loginAccount.setState(LoginUserStates.NORMAL.getCode());
                        loginAccount.setPassword("123456");
                        baseLoginAccountService.save(loginAccount);
                    } else {
                        loginAccount.setUserName(uBean.getAccount());
                        Integer loginHistory = loginAccount.getLoginHistory();
                        if (loginHistory != null && loginHistory == 1) {
                            loginAccount.setFirstLogin(0);
                        }
                        baseLoginAccountDao.save(loginAccount);
                    }
                }
                //更新岗位人数
                List<BaseUser> uList = baseUserDao.findByJob(jobMap.get(uBean.getJobName()));
                BpJob bpJob = bpJobDao.findById(jobMap.get(uBean.getJobName())).get();
                if (!CollectionUtils.isEmpty(uList)) {
                    bpJob.setStaffCount(uList.size());
                } else {
                    bpJob.setStaffCount(0);
                }
                bpJobDao.save(bpJob);
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("人员第{%s}行:数据过长", uBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("人员第{%s}行:数据异常", uBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        if (!CollectionUtils.isEmpty(syncMap) && syncOpen) {
            List<Long> allIds = new ArrayList<>();
            Set<Map.Entry<Long, BaseUser>> entryseSet = syncMap.entrySet();
            for (Map.Entry<Long, BaseUser> entry : entryseSet) {
                allIds.add(entry.getKey());
            }
            List<BaseUser> syncList = syncMap.values().stream().collect(toList());
            Map<String, BaseUser> idMap = syncList.stream().collect(Collectors.toMap(r -> r.getUniqueId(), r -> r));
            List<Long> unSyncIds = new ArrayList<>();
            List<SyncBatchDataReturnBean> returnBeans = locateServerService.syncSaveUser(syncList, locateServerService.getBuildId(), locateServerService.getLoginToken());
            if (!CollectionUtils.isEmpty(returnBeans)) {
                for (SyncBatchDataReturnBean bean : returnBeans) {
                    if (idMap.get(bean.getUniqueId()) != null) {
                        unSyncIds.add(idMap.get(bean.getUniqueId()).getId());
                    }
                }
            }
            if (!CollectionUtils.isEmpty(unSyncIds)) {
                allIds.removeAll(unSyncIds);
                baseUserDao.editLocateSyncByIds(unSyncIds, Integer.valueOf(0));
            }
            if (!CollectionUtils.isEmpty(allIds)) {
                baseUserDao.editLocateSyncByIds(allIds, Integer.valueOf(1));
            }
        }
        //每个新增用户添加默认角色： 员工
        if (!userList.isEmpty()) {
            addDefaultRole4User(userList);
        }
        return returnList(errors, count, error, ignore, "人员");
    }

    //每个新增用户添加默认角色： 员工
    @Async
    public void addDefaultRole4User(List<BaseUser> userList) {
        //获取用户默认角色： 员工
        BaseRole baseRole = baseRoleDao.findFirstByName(Constants.USER_DEFAULT_ROLE_NAME);
        List<BaseRoleUserLoginRole> userRoleList = new ArrayList<>();
        if (baseRole != null && userList != null) {
            for (BaseUser baseUser : userList) {
                BaseRoleUserLoginRole userRole = new BaseRoleUserLoginRole();
                userRole.setUserId(baseUser.getId());
                userRole.setRoleId(baseRole.getId());
                userRoleList.add(userRole);
            }
            if (!userRoleList.isEmpty()) {
                baseRoleUserLoginRoleDao.saveAll(userRoleList);
            }
        }
    }

    /**
     * 人员邮箱导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importUserEmailByExcel(MultipartFile file) {
        List<ExcelUserEmailBean> eBeans = parseData(file, 0, ExcelUserEmailBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < eBeans.size(); i++) {
            ExcelUserEmailBean eBean = eBeans.get(i);
            if (StringUtils.isBlank(eBean.getCode())) {
                errors.add(String.format("人员邮箱导入第{%s}行:人员工号不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtils.isBlank(eBean.getEmail())) {
                errors.add(String.format("人员邮箱导入第{%s}行:人员邮箱不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            //保存员工信息
            try {
                BaseUser user = baseUserDao.findByCode(eBean.getCode());
                if (user == null) {
                    errors.add(String.format("人员邮箱导入第{%s}行:人员不存在", eBean.getRowIndex()));
                    error++;
                    continue;
                }
                user.setEmail(eBean.getEmail());
                if (StringUtils.isNotBlank(eBean.getRealName())) {
                    user.setRealName(eBean.getRealName());
                }
                if (StringUtils.isNotBlank(eBean.getTelephone())) {
                    user.setTelephone(eBean.getTelephone());
                }
                baseUserDao.save(user);
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("人员邮箱导入第{%s}行:数据过长常", eBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("人员邮箱导入第{%s}行:数据异常", eBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "人员邮箱导入");
    }

    /**
     * 试题导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importQuestionByExcel(MultipartFile file) {
        List<ExcelEduQuestionBean> eBeans = parseData(file, 0, ExcelEduQuestionBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        List<String> answers = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H"));
        for (int i = 0; i < eBeans.size(); i++) {
            ExcelEduQuestionBean eBean = eBeans.get(i);
            if (StringUtils.isBlank(eBean.getQuestionTypeName())) {
                errors.add(String.format("试题导入第{%s}行:试题类型不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtils.isBlank(eBean.getName())) {
                errors.add(String.format("试题导入第{%s}行:试题名称不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtils.isBlank(eBean.getType())) {
                errors.add(String.format("试题导入第{%s}行:题型不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtils.isBlank(eBean.getAnswer())) {
                errors.add(String.format("试题导入第{%s}行:答案不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            if (!"判断题".equals(eBean.getType()) && StringUtils.isBlank(eBean.getQuestionA())) {
                errors.add(String.format("试题导入第{%s}行:选项A不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            if (!"判断题".equals(eBean.getType()) && StringUtils.isBlank(eBean.getQuestionB())) {
                errors.add(String.format("试题导入第{%s}行:选项B不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                //获取试题类型
                Long number = commonTypeDao.countOfName("试题", eBean.getQuestionTypeName());
                CommonType cType = null;
                if (number == 0) {
                    CommonType commonType = new CommonType();
                    commonType.setName(eBean.getQuestionTypeName());
                    commonType.setType("试题");
                    commonType.setObjCount(0);
                    cType = commonTypeDao.save(commonType);
                } else {
                    cType = commonTypeDao.findQuestionTypeName(eBean.getQuestionTypeName());
                }
//                //保存试题
//                List<EduQuestion> eduQuestions = eduQuestionDao.findByTypeAndNameAndQuestionTypeId(getQuestionType(eBean.getType()), eBean.getName(), cType.getId());
//                if (!CollectionUtils.isEmpty(eduQuestions)) {
//                    errors.add(String.format("试题导入第{%s}行:试题已存在", eBean.getRowIndex()));
//                    ignore++;
//                    continue;
//                }
                EduQuestion content = new EduQuestion();
                content.setCode(bizCodeGeneratorFacade.shiTi());
                content.setCreateUserName(baseUserDao.getBaseUserNameById(Context.getCurrentUserId()));
                //答案
                List<String> answer = Arrays.asList(eBean.getAnswer().split(","));
                boolean flag = true;
                if ("判断题".equals(eBean.getType())) {
                    if (answer.size() > 1) {
                        errors.add(String.format("试题导入第{%s}行:判断题答案只能有一个", eBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    if (answer.size() == 0 || !answers.contains(answer.get(0))) {
                        errors.add(String.format("试题导入第{%s}行:答案请从A,B中选择", eBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    if ("A".equals(answer.get(0))) {
                        content.setAnswer("是");
                    } else if ("B".equals(answer.get(0))) {
                        content.setAnswer("否");
                    } else {
                        errors.add(String.format("试题导入第{%s}行:判断题答案请填写A或者B", eBean.getRowIndex()));
                        error++;
                        continue;
                    }
                } else if ("单选题".equals(eBean.getType())) {
                    if (answer.size() > 1) {
                        errors.add(String.format("试题导入第{%s}行:单选题答案自能有一个", eBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    if (answer.size() == 0 || !answers.contains(answer.get(0))) {
                        errors.add(String.format("试题导入第{%s}行:答案请从A,B,C,D,E,F,G,H中选择", eBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    content.setAnswer(answer.get(0));
                } else if ("多选题".equals(eBean.getType())) {
                    if (answer.size() == 0) {
                        errors.add(String.format("试题导入第{%s}行:答案请从A,B,C,D,E,F,G,H中选择", eBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    for (String s : answer) {
                        if (!answers.contains(s)) {
                            errors.add(String.format("试题导入第{%s}行:答案请从A,B,C,D,E,F,G,H中选择,多个答案用逗号拼接" + "", eBean.getRowIndex()));
                            error++;
                            flag = false;
                            continue;
                        }
                    }
                    content.setAnswer(Joiner.on(",").join(answer));
                }
                if (!flag) {
                    continue;
                }
                content.setName(eBean.getName());
                content.setType(getQuestionType(eBean.getType()));
                content.setQuestionTypeId(cType.getId());
                EduQuestion question = eduQuestionDao.save(content);
                //保存各个选项
                saveQuestionItem(eBean, question.getId());
                //更新题型数量
                if (cType != null) {
                    commonTypeService.updateTypeCount(CommonTypes.QUESTION, cType.getId());
                }
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("试题导入第{%s}行:数据过长", eBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("试题导入第{%s}行:数据异常", eBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "试题导入");
    }

    /**
     * 视频设备导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> imporVideoByExcel(MultipartFile file) {
        List<ExcelVideoBean> eBeans = parseData(file, 0, ExcelVideoBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < eBeans.size(); i++) {
            ExcelVideoBean bean = eBeans.get(i);
            if (StringUtils.isBlank(bean.getBrand())) {
                errors.add(String.format("视频设备导入第{%s}行:视频设备品牌不能为空", bean.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtils.isBlank(bean.getName())) {
                errors.add(String.format("视频设备导入第{%s}行:视频设备名称不能为空", bean.getRowIndex()));
                error++;
                continue;
            }
//            int co = bpSystemVideoDao.countByNameAndBrand(bean.getName(), bean.getBrand());
//            if (co > 0) {
//                errors.add(String.format("视频设备导入第{%s}行:该品牌下,视频设备名称已存在", bean.getRowIndex()));
//                error++;
//                continue;
//            }
            if (StringUtils.isBlank(bean.getEvaluationName())) {
                errors.add(String.format("视频设备导入第{%s}行:所在风险区域不能为空", bean.getRowIndex()));
                error++;
                continue;
            }
            List<Long> rList = riskDistrictDao.findIdByName(bean.getEvaluationName());
            if (org.springframework.util.CollectionUtils.isEmpty(rList)) {
                errors.add(String.format("视频设备导入第{%s}行:所在风险区域不存在", bean.getRowIndex()));
                error++;
                continue;
            }
            if (bean.getBrand().equals("海康") || bean.getBrand().equals("大华")) {
                if (checkItemIsNull(bean) == 1) {
                    if (StringUtils.isBlank(bean.getRealTimeSite())) {
                        bean.setRealTimeSite("rtsp://" + bean.getAccount() + ":" + bean.getPassword() + "@" + bean.getIp() + ":" + bean.getPort() +
                                "/Streaming/Channels/" + bean.getChannelNo() + "01?transportmode=unicast");
                    }
                    if (StringUtils.isBlank(bean.getHistorySite())) {
                        bean.setHistorySite("p://" + bean.getAccount() + ":" + bean.getPassword() + "@" + bean.getIp() + ":" + bean.getPort() +
                                "/Streaming/Channels/" + bean.getChannelNo() + "01?starttime={startDate}t{startTime}z&endtime={endDate}t{endTime}z");
                    }
                } else {
                    if (StringUtils.isBlank(bean.getRealTimeSite())) {
                        errors.add(String.format("视频设备导入第{%s}行:实时视频流地址预览不能为空", bean.getRowIndex()));
                        error++;
                        continue;
                    }
                    if (StringUtils.isBlank(bean.getHistorySite())) {
                        errors.add(String.format("视频设备导入第{%s}行:历史视频流地址预览不能为空", bean.getRowIndex()));
                        error++;
                        continue;
                    }
                }

            } else if (bean.getBrand().equals("其它")) {
                if (StringUtils.isBlank(bean.getRealTimeSite())) {
                    errors.add(String.format("视频设备导入第{%s}行:实时视频流地址预览不能为空", bean.getRowIndex()));
                    error++;
                    continue;
                }
                if (StringUtils.isBlank(bean.getHistorySite())) {
                    errors.add(String.format("视频设备导入第{%s}行:历时视频流地址预览不能为空", bean.getRowIndex()));
                    error++;
                    continue;
                }
                if (bean.getDateFormat() == null) {
                    errors.add(String.format("视频设备导入第{%s}行:地址日期格式不能为空", bean.getRowIndex()));
                    error++;
                    continue;
                }
                if (bean.getTimeFormat() == null) {
                    errors.add(String.format("视频设备导入第{%s}行:地址时间格式不能为空", bean.getRowIndex()));
                    error++;
                    continue;
                }
            }
            try {
                BpSystemVideo video = new BpSystemVideo();
                List<BpSystemVideo> vList = bpSystemVideoDao.findByNameAndBrand(bean.getName(), bean.getBrand());
                if (!CollectionUtils.isEmpty(vList)) {
                    video = vList.get(0);
                } else {
                    if (StringUtils.isBlank(bean.getDateFormat())) {
                        bean.setDateFormat("yyyy-MM-dd");
                    }
                    if (StringUtils.isBlank(bean.getTimeFormat())) {
                        bean.setTimeFormat("mm:HH:dd");
                    }
                }
                BeanUtils.copyProperties(bean, video);
                video.setEvaluation(rList.get(0).toString());
                bpSystemVideoDao.save(video);
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("视频设备导入第{%s}行:数据过长", bean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (BeansException e) {
                errors.add(String.format("视频设备导入第{%s}行:数据异常", bean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "视频设备导入");
    }

    /**
     * 风险区域导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importRiskDistrictByExcel(MultipartFile file) {
//        List<ExcelRiskDistrictBean> eBeans = parseData(file, 0, ExcelRiskDistrictBean.class, true);
//        List<BpDepart> deptList = getOwnedAuthDeptCodeMapping();
//        Map<String, Long> departCountMap = this.getDepartCountMap(deptList);
//        Map<String, BpDepart> nameDeptMap = this.getNameDeptMap(deptList);
//        int count = 0;
//        int error = 0;
//        int ignore = 0;
//        List<String> errors = new ArrayList<>();
//        for (int i = 0; i < eBeans.size(); i++) {
//            ExcelRiskDistrictBean bean = eBeans.get(i);
//            if (StringUtils.isBlank(bean.getName())) {
//                errors.add(String.format("风险区域导入第{%s}行:风险区域名称不能为空", bean.getRowIndex()));
//                error++;
//                continue;
//            }
//            if (StringUtils.isBlank(bean.getCode())) {
//                errors.add(String.format("风险区域导入第{%s}行:风险区域编号不能为空", bean.getRowIndex()));
//                error++;
//                continue;
//            }
//
//            List<RiskDistrict> riskDistricts = riskDistrictDao.findByCode(bean.getCode());
//            RiskDistrictSaveBean riskDistrictBean = new RiskDistrictSaveBean();
//            if (CollectionUtils.isEmpty(riskDistricts)) {
//                riskDistrictBean = new RiskDistrictSaveBean();
//            } else {
//                errors.add(String.format("风险区域导入第{%s}行:风险区域已存在", bean.getRowIndex()));
//                ignore++;
//                continue;
//            }
//            List<RiskDistrict> names = riskDistrictDao.findByName(bean.getName());
//            if (!CollectionUtils.isEmpty(names)) {
//                errors.add(String.format("风险区域导入第{%s}行:风险区域名称已存在", bean.getRowIndex()));
//                error++;
//                continue;
//            }
//            String errorMsg = checkDataAuth(bean.getResponsibleDeptParentName(), bean.getResponsibleDeptName(), nameDeptMap, departCountMap);
//            if (!StringUtils.isBlank(errorMsg)) {
//                errors.add(String.format(errorMsg, "风险区域", bean.getRowIndex()));
//                error++;
//                continue;
//            }
//            riskDistrictBean.setCode(bean.getCode());
//            riskDistrictBean.setName(bean.getName());
//            riskDistrictBean.setRemark(bean.getRemark());
//            Long responsibleDeptId;
//            if (departCountMap.get(bean.getResponsibleDeptName()) > 1) {
//                responsibleDeptId = findDeptIdByParentDeptName(deptList, bean.getResponsibleDeptName(), bean.getResponsibleDeptParentName());
//                if (responsibleDeptId == null) {
//                    error++;
//                    errors.add(String.format("风险区域第{%s}行:部门存在多个且直属上级部门未找到", bean.getRowIndex()));
//                    continue;
//                }
//            } else {
//                responsibleDeptId = nameDeptMap.get(bean.getResponsibleDeptName()).getId();
//            }
//            Long rsDeptId = responsibleDeptId == null ? null : responsibleDeptId.longValue();
//            RiskDistrictSaveBean.setResponsibleDept(rsDeptId);
//            if (StringUtils.isNotBlank(bean.getRiskLevelName())) {
//                if (RiskLevels.findByName(bean.getRiskLevelName()) == null) {
//                    errors.add(String.format("风险区域导入第{%s}行:风险等级不存在", bean.getRowIndex()));
//                    error++;
//                    continue;
//                }
//                RiskDistrictSaveBean.setRiskLevel(RiskLevels.findByName(bean.getRiskLevelName()).getCode());
//            }
//            try {
//                riskDistrictService.add(RiskDistrictSaveBean);
//                count++;
//            } catch (DataIntegrityViolationException e) {
//                errors.add(String.format("风险区域导入第{%s}行:数据过长", bean.getRowIndex()));
//                error++;
//                log.error(e.getMessage(), e);
//            } catch (Exception e) {
//                errors.add(String.format("风险区域导入第{%s}行:数据异常", bean.getRowIndex()));
//                error++;
//                log.error(e.getMessage(), e);
//            }
//        }
//        return returnList(errors, count, error, ignore, "风险区域导入");
        return new ArrayList<>();
    }

    private int checkItemIsNull(ExcelVideoBean bean) {
        int flag = 0;
        if (StringUtils.isNotBlank(bean.getAccount())) {
            flag = 1;
        }
        if (StringUtils.isNotBlank(bean.getPassword())) {
            flag = 1;
        }
        if (StringUtils.isNotBlank(bean.getIp())) {
            flag = 1;
        }
        if (bean.getPort() != null) {
            flag = 1;
        }
        if (StringUtils.isNotBlank(bean.getChannelNo())) {
            flag = 1;
        }
        return flag;
    }

    private void saveQuestionItem(ExcelEduQuestionBean eBean, Long qId) {
        EduQuestionItem a = new EduQuestionItem();
        EduQuestionItem b = new EduQuestionItem();
        if (eBean.getType().equals("判断题")) {
            a.setChoiceCode("是");
            b.setChoiceCode("否");
        } else {
            a.setChoiceCode("A");
            a.setContent(eBean.getQuestionA());
            b.setChoiceCode("B");
            b.setContent(eBean.getQuestionB());
        }
        a.setIndexNo(0);
        a.setQuestionId(qId);
        b.setIndexNo(1);
        b.setQuestionId(qId);
        eduQuestionItemDao.save(a);
        eduQuestionItemDao.save(b);
        if (!eBean.getType().equals("判断题")) {
            if (StringUtils.isNotBlank(eBean.getQuestionC())) {
                EduQuestionItem c = new EduQuestionItem();
                c.setChoiceCode("C");
                c.setContent(eBean.getQuestionC());
                c.setIndexNo(2);
                c.setQuestionId(qId);
                eduQuestionItemDao.save(c);
            }
            if (StringUtils.isNotBlank(eBean.getQuestionD())) {
                EduQuestionItem d = new EduQuestionItem();
                d.setChoiceCode("D");
                d.setContent(eBean.getQuestionD());
                d.setIndexNo(3);
                d.setQuestionId(qId);
                eduQuestionItemDao.save(d);
            }
            if (StringUtils.isNotBlank(eBean.getQuestionE())) {
                EduQuestionItem e = new EduQuestionItem();
                e.setChoiceCode("E");
                e.setContent(eBean.getQuestionE());
                e.setIndexNo(4);
                e.setQuestionId(qId);
                eduQuestionItemDao.save(e);
            }
            if (StringUtils.isNotBlank(eBean.getQuestionF())) {
                EduQuestionItem f = new EduQuestionItem();
                f.setChoiceCode("F");
                f.setContent(eBean.getQuestionF());
                f.setIndexNo(5);
                f.setQuestionId(qId);
                eduQuestionItemDao.save(f);
            }
            if (StringUtils.isNotBlank(eBean.getQuestionG())) {
                EduQuestionItem g = new EduQuestionItem();
                g.setChoiceCode("G");
                g.setContent(eBean.getQuestionG());
                g.setIndexNo(6);
                g.setQuestionId(qId);
                eduQuestionItemDao.save(g);
            }
            if (StringUtils.isNotBlank(eBean.getQuestionH())) {
                EduQuestionItem h = new EduQuestionItem();
                h.setChoiceCode("H");
                h.setContent(eBean.getQuestionH());
                h.setIndexNo(7);
                h.setQuestionId(qId);
                eduQuestionItemDao.save(h);
            }
        }
    }

    private String getQuestionType(String type) {
        if (type.equals("单选题")) {
            return "S";
        } else if (type.equals("多选题")) {
            return "M";
        } else if (type.equals("判断题")) {
            return "J";
        } else {
            return "";
        }
    }


    /**
     * 工业管道导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importPipeByExcel(MultipartFile file) {
        List<IndustrialPipeBean> iBeans = parseData(file, 0, IndustrialPipeBean.class, true);
        List<BpDepart> deptList = getOwnedAuthDeptCodeMapping();
        Map<String, Long> departCountMap = this.getDepartCountMap(deptList);
        Map<String, BpDepart> nameDeptMap = this.getNameDeptMap(deptList);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < iBeans.size(); i++) {
            IndustrialPipeBean iBean = iBeans.get(i);
            if (StringUtils.isBlank(iBean.getCode())) {
                errors.add(String.format("工业管道第{%s}行:工业管道编号不能为空", iBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(iBean.getName())) {
                errors.add(String.format("工业管道第{%s}行:工业管道名称不能为空", iBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(iBean.getCurrentState())) {
                errors.add(String.format("工业管道第{%s}行:工业管道目前状态不能为空", iBean.getRowIndex()));
                error++;
                continue;
            }
            String errorMsg = this.checkDataAuth(iBean.getResponsibleDeptParentName(), iBean.getResponsibleDeptName(), nameDeptMap, departCountMap);
            if (!StringUtils.isBlank(errorMsg)) {
                errors.add(String.format(errorMsg, "工业管道", iBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                BpIndustrialPipeline bp = new BpIndustrialPipeline();
                if (bpIndustrialPipelineDao.findByCode(iBean.getCode()) != null) {
                    bp = bpIndustrialPipelineDao.findByCode(iBean.getCode());
                }
                BeanUtils.copyProperties(iBean, bp);
                //投产日期
                if (StringUtils.isNotBlank(iBean.getCommissioningDate())) {
                    try {
                        bp.setCommissioningDate(DateUtil.parse(iBean.getCommissioningDate()));
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        errors.add(String.format("工业管道第{%s}行:投产日期错误", iBean.getRowIndex()));
                        continue;
                    }
                } else {
                    bp.setCommissioningDate(null);
                }
                String cState = iBean.getCurrentState();
                if ("运行".equals(cState)) {
                    bp.setCurrentState(0);
                } else if ("检修".equals(cState)) {
                    bp.setCurrentState(2);
                } else if ("停产".equals(cState)) {
                    bp.setCurrentState(1);
                } else {
                    bp.setCurrentState(null);
                }

                if (StringUtils.isNotBlank(iBean.getPressureLevel()) && (!iBean.getPressureLevel().equals("低压")
                        && !iBean.getPressureLevel().equals("中压") && !iBean.getPressureLevel().equals("高压") && !iBean.getPressureLevel().equals("超高压"))) {
                    errors.add(String.format("工业管道第{%s}行:工业管道压力等级请从低压,中压,高压,超高压中选择", iBean.getRowIndex()));
                    error++;
                    continue;
                }
                String ipp = iBean.getIsPressurePipeline();
                if ("是".equals(ipp)) {
                    bp.setIsPressurePipeline("Y");
                } else if ("否".equals(ipp)) {
                    bp.setIsPressurePipeline("N");
                    bp.setPressureLevel(null);
                } else {
                    bp.setIsPressurePipeline(null);
                    bp.setPressureLevel(null);
                }
                String hName = iBean.getHchName();
                if (hName != null) {
                    bp.setHchName(hName);
                    MhMajorHazardChemProduct hProduct = mhMajorHazardChemProductDao.findByName(hName);
                    if (hProduct != null) {
                        bp.setHchId(hProduct.getId());
                        bp.setCas(hProduct.getCasNo());
                    }
                }
                String isp = iBean.getIsHchPipeline();
                if ("是".equals(isp)) {
                    bp.setIsHchPipeline("Y");
                } else if ("否".equals(isp)) {
                    bp.setIsHchPipeline("N");
                    bp.setHchId(null);
                    bp.setCas(null);
                    bp.setHchName(null);
                } else {
                    bp.setIsHchPipeline(null);
                    bp.setHchId(null);
                    bp.setCas(null);
                    bp.setHchName(null);
                }

                if (iBean.getOpPressureHighValue() != null && iBean.getOpPressureLowValue() != null && iBean.getOpPressureHighValue() < iBean.getOpPressureLowValue()) {
                    errors.add(String.format("工业管道第{%s}行:工业管道操作压力上限不能小于下限", iBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (iBean.getOpTemperatureHighValue() != null && iBean.getOpTemperatureLowValue() != null && iBean.getOpTemperatureHighValue() < iBean.getOpTemperatureLowValue()) {
                    errors.add(String.format("工业管道第{%s}行:工业管道操作温度上限不能小于下限", iBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (iBean.getWorkPressureHighValue() != null && iBean.getWorkPressureLowValue() != null && iBean.getWorkPressureHighValue() < iBean.getWorkPressureLowValue()) {
                    errors.add(String.format("工业管道第{%s}行:工业管道工作压力上限不能小于下限", iBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (iBean.getWorkTemperatureHighValue() != null && iBean.getWorkTemperatureLowValue() != null && iBean.getWorkTemperatureHighValue() < iBean.getWorkTemperatureLowValue()) {
                    errors.add(String.format("工业管道第{%s}行:工业管道工作温度上限不能小于下限", iBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (StringUtils.isBlank(bp.getUniCode())) {
                    bp.setUniCode(bizCodeGeneratorFacade.gongYeGuanDao());
                }
                Long responsibleDeptId;
                if (departCountMap.get(iBean.getResponsibleDeptName()) > 1) {
                    responsibleDeptId = findDeptIdByParentDeptName(deptList, iBean.getResponsibleDeptName(), iBean.getResponsibleDeptParentName());
                    if (responsibleDeptId == null) {
                        error++;
                        errors.add(String.format("风险区域第{%s}行:部门存在多个且直属上级部门未找到", iBean.getRowIndex()));
                        continue;
                    }
                } else {
                    responsibleDeptId = nameDeptMap.get(iBean.getResponsibleDeptName()).getId();
                }
                bp.setResponsibleDept(responsibleDeptId);
                bp = bpIndustrialPipelineDao.save(bp);
                bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(DeviceFacilityTypes.GONG_YE_GUAN_DAO, bp.getId(), bp.getCode(), bp.getName(), null, null, null);
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("工业管道第{%s}行:数据过长", iBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("工业管道第{%s}行:数据异常", iBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }

        return returnList(errors, count, error, ignore, "工业管道");
    }


    /**
     * 危化品导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> imporHazardousChemicalsByExcel(MultipartFile file) {
        List<HchBean> hBeans = parseData(file, 0, HchBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < hBeans.size(); i++) {
            HchBean hBean = hBeans.get(i);
            if (StringUtils.isBlank(hBean.getCode())) {
                errors.add(String.format("危化品第{%s}行:危化品编码不能为空", hBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(hBean.getName())) {
                errors.add(String.format("危化品第{%s}行:危化品名称不能为空", hBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(hBean.getCasNo())) {
                errors.add(String.format("危化品第{%s}行:危化品CAS号不能为空/CAS号格式不正确,请在CAS号前加英文单引号 ' ", hBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(hBean.getKeySupervisorHch())) {
                errors.add(String.format("危化品第{%s}行:危化品是否重点监管危险化学品不能为空", hBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                MhMajorHazardChemProduct mProduct = new MhMajorHazardChemProduct();
                MhMajorHazardChemProduct p = mhMajorHazardChemProductDao.findByName(hBean.getCode());

                if (p != null) {
                    if (mhMajorHazardChemProductDao.countByNameAndCodeNotEq(hBean.getName(), hBean.getCode()) > 0) {
                        errors.add(String.format("危化品第{%s}行:危化品名称已存在", hBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    List<MhMajorHazardChemProduct> mpList = mhMajorHazardChemProductDao.getByCasNoAndCodeNotEq(hBean.getCasNo(), hBean.getCode());
                    if (!org.springframework.util.CollectionUtils.isEmpty(mpList)) {
                        errors.add(String.format("危化品第{%s}行:危化品CAS号已存在", hBean.getRowIndex()));
                        count++;
                        continue;
                    }
                    mProduct = p;
                } else {
                    if (mhMajorHazardChemProductDao.countByName(hBean.getName()) > 0) {
                        errors.add(String.format("危化品第{%s}行:危化品名称已存在", hBean.getRowIndex()));
                        count++;
                        continue;
                    }
                    List<MhMajorHazardChemProduct> mpList = mhMajorHazardChemProductDao.getByCasNo(hBean.getCasNo());
                    if (!org.springframework.util.CollectionUtils.isEmpty(mpList)) {
                        errors.add(String.format("危化品第{%s}行:危化品CAS号已存在", hBean.getRowIndex()));
                        count++;
                        continue;
                    }
                }
                mProduct.setCode(hBean.getCode());
                mProduct.setName(hBean.getName());
                mProduct.setAlias(hBean.getAlias());
                mProduct.setEngName(hBean.getEnName());
                mProduct.setCasNo(hBean.getCasNo());
                mProduct.setType(hBean.getDangerType());
                String key = hBean.getKeySupervisorHch();
                if ("是".equals(key)) {
                    mProduct.setHazardChemicalFlag(String.valueOf(1));
                } else if ("否".equals(key)) {
                    mProduct.setHazardChemicalFlag(String.valueOf(0));
                } else {
                    mProduct.setHazardChemicalFlag(null);
                }
                mhMajorHazardChemProductDao.save(mProduct);
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("危化品第{%s}行:数据过长", hBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("危化品第{%s}行:数据异常", hBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "危化品");
    }

    /**
     * 重大危险源导入
     * <p>
     * excel表中一条数据要分别在数据库中的危险源表和危化品附属表录入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> imporDangerouSourceByExcel(MultipartFile file) {
        List<MajorHazardBean> mBeans = parseData(file, 0, MajorHazardBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < mBeans.size(); i++) {
            MajorHazardBean mBean = mBeans.get(i);
            if (StringUtils.isBlank(mBean.getCode())) {
                errors.add(String.format("重大危险源第{%s}行:重大危险源编码不能为空", mBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(mBean.getName())) {
                errors.add(String.format("重大危险源第{%s}行:重大危险源名称不能为空", mBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(mBean.getRiskDistrictCode())) {
                errors.add(String.format("重大危险源第{%s}行:所在风险区域编码不能为空", mBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(mBean.getHchRelBean().getHchName())) {
                errors.add(String.format("重大危险源第{%s}行:危化品名称不能为空", mBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(mBean.getLevel())) {
                errors.add(String.format("重大危险源第{%s}行:重大危险源等级不能为空", mBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(mBean.getHchRelBean().getCasNo())) {
                errors.add(String.format("重大危险源第{%s}行:CAS号不能为空", mBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                // 危险源
                boolean mhExist = false;
                MhMajorHazard mh = new MhMajorHazard();
                MhMajorHazard m = mhMajorHazardDao.findByCode(mBean.getCode());
                if (m != null) {
                    List<MhMajorHazard> mList = mhMajorHazardDao.findByNameAndStateAndIdNotEq(mBean.getName(), m.getId());
                    if (!CollectionUtils.isEmpty(mList)) {
                        errors.add(String.format("重大危险源第{%s}行:新增危险源名称已存在", mBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    mh = m;
                    mhExist = true;
                } else {
                    List<MhMajorHazard> mList = mhMajorHazardDao.findByNameAndState(mBean.getName());
                    if (!CollectionUtils.isEmpty(mList)) {
                        errors.add(String.format("重大危险源第{%s}行:新增危险源名称已存在", mBean.getRowIndex()));
                        error++;
                        continue;
                    }
                }
                mh.setCode(mBean.getCode());
                mh.setName(mBean.getName());
                // 获取风险区域id
                List<RiskDistrict> rList = riskDistrictDao.findByCode(mBean.getRiskDistrictCode());
                if (org.springframework.util.CollectionUtils.isEmpty(rList)) {
                    errors.add(String.format("重大危险源第{%s}行:所在风险区域不存在", mBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (!CollectionUtils.isEmpty(rList)) {
                    List<Long> deptIds = dataAuthService.findDepartIdsByCurUser();
                    List<Long> responsibleDepts = rList.stream().map(RiskDistrict::getResponsibleDept).collect(toList());
                    List<Long> intersection = responsibleDepts.stream().filter(item -> deptIds.contains(Long.valueOf(item))).collect(toList());
                    if (CollectionUtils.isEmpty(intersection)) {
                        errors.add(String.format("重大危险源第{%s}行:无权限导入该风险区域数据", mBean.getRowIndex()));
                        error++;
                        continue;
                    }
                }

                mh.setRiskDistrictId(rList.get(0).getId());
                // 重大危险源描述
                mh.setDescription(mBean.getDescription());
                // 防雷防静电设施是否定期接受检测
                String ap = mBean.getAntiThunderDeviceCheckedPeriodly();
                if ("是".equals(ap)) {
                    mh.setAntiThunderFacilityPeriodlyChecked("Y");
                } else if ("否".equals(ap)) {
                    mh.setAntiThunderFacilityPeriodlyChecked("N");
                } else {
                    mh.setAntiThunderFacilityPeriodlyChecked(null);
                }
                mh.setMinDistance(mBean.getMinDistance());
                mh.setSurroundingSafeDistance(mBean.getSurroundingSafeDistance());
                // R值
                mh.setRvalue(mBean.getR());
                // 重大危险源等级
                mh.setLevel(mBean.getLevel());
                // 重大危险源投用时间
                mh.setStartUseTime(mBean.getInProductionDate());
                // 填表人
                mh.setWrittenBy(mBean.getCreator());
                if (StringUtils.isNotBlank(mBean.getResponsibleUserCode())) {
                    BaseUser responsibleUser = baseUserDao.findByCode(mBean.getResponsibleUserCode());
                    if (responsibleUser != null) {
                        mh.setResponsibleUserId(responsibleUser.getId().toString());
                    }
                }
                MhMajorHazardChemProduct mProduct = mhMajorHazardChemProductDao
                        .findByCasNo(mBean.getHchRelBean().getCasNo());
                if (mProduct == null) {
                    errors.add(String.format("重大危险源第{%s}行:危化品不存在", mBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (!mProduct.getName().equals(mBean.getHchRelBean().getHchName())) {
                    errors.add(String.format("重大危险源第{%s}行:危化品名称与CAS号不匹配", mBean.getRowIndex()));
                    error++;
                    continue;
                }
                mh = mhMajorHazardDao.save(mh);
                if (!mhExist) {
                    // 1.危险源不存在,危化品存在,则保存危险源 和危化品详情表
                    MhMajorHazardChemProductRel mhr = this.getMhProductRel(mBean, new MhMajorHazardChemProductRel());
                    mhr.setMajorHazardId(mh.getId());
                    mhr.setMhMajorHazardChemProduct(mProduct);
                    mhMajorHazardChemProductRelDao.save(mhr);
                    count++;
                } else {
                    Long mId = mh.getId();
                    // 2.危险源存在,危化品存在,判断危险品详情表是否已经保存该数据
                    List<MhMajorHazardChemProductRel> relList = mhMajorHazardChemProductRelDao.findIdByPidAndMid(mProduct.getId(), mId);
                    if (CollectionUtils.isEmpty(relList)) {
                        //未保存--新增
                        MhMajorHazardChemProductRel mhr = this.getMhProductRel(mBean, new MhMajorHazardChemProductRel());
                        mhr.setMajorHazardId(mId);
                        mhr.setMhMajorHazardChemProduct(mProduct);
                        mhMajorHazardChemProductRelDao.save(mhr);
                        count++;
                    } else {
                        //已保存--修改
                        MhMajorHazardChemProductRel mhr = this.getMhProductRel(mBean, relList.get(0));
                        mhr.setMajorHazardId(mId);
                        mhr.setMhMajorHazardChemProduct(mProduct);
                        mhMajorHazardChemProductRelDao.save(mhr);
                        count++;
                    }
                }
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("重大危险源第{%s}行:数据过长", mBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("重大危险源第{%s}行:数据异常", mBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "重大危险源");
    }

    private MhMajorHazardChemProductRel getMhProductRel(MajorHazardBean mBean, MhMajorHazardChemProductRel mhr) {

        // 生产用途
        mhr.setUsage(mBean.getHchRelBean().getProductionUsage());
        // 物理状态
        mhr.setSubstanceStatus(mBean.getHchRelBean().getPhysicalState());
        // 危化品性质
        mhr.setChemProductFeature(
                mBean.getHchRelBean().getHchCharacter() == null ? "" : mBean.getHchRelBean().getHchCharacter());
        // 操作温度
        mhr.setOperationTemperature(mBean.getHchRelBean().getOpTemprature());
        // 操作压力
        mhr.setOperationPressure(mBean.getHchRelBean().getOpPressure());
        // 存量
        mhr.setStock(mBean.getHchRelBean().getStorage());
        // 设计存量
        mhr.setDesignStock(mBean.getHchRelBean().getDesignedStorage());
        // 临界量
        mhr.setCriticalStock(mBean.getHchRelBean().getRestrictLimitStorage());
        // 校正系数
        mhr.setFixRate(mBean.getHchRelBean().getReviseFactor());
        return mhr;
    }

    /**
     * 设备装置导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> equipmentAndFacilities(MultipartFile file) {
        List<ProductionFacilityBean> pBeans = parseData(file, 0, ProductionFacilityBean.class, true);
        List<BpDepart> deptList = this.getOwnedAuthDeptCodeMapping();
        Map<String, Long> departCountMap = this.getDepartCountMap(deptList);
        Map<String, BpDepart> nameDeptMap = this.getNameDeptMap(deptList);
//        Date date = DateUtil.parse(dateStr);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        // 部门
        Map<String, Long> departMap = new HashMap<>();
        List<BpDepart> departList = bpDepartDao.findAll();
        if (!CollectionUtils.isEmpty(departList)) {
            for (BpDepart bpDepart : departList) {
                departMap.put(bpDepart.getCode(), bpDepart.getId());
            }
        }
        List<RiskDistrict> districts = riskDistrictService.findByResponsibleDept();
        Map<String, Long> districtCodeMap = districts.stream().collect(Collectors.toMap(RiskDistrict::getCode, RiskDistrict::getId, (k1, k2) -> k2));
        Map<String, MhMajorHazard> hazardCodeMap = this.getHazardCodeMap();
        Map<String, Long> pointCodeMap = this.getPointCodeMap();

        for (int i = 0; i < pBeans.size(); i++) {
            ProductionFacilityBean pBean = pBeans.get(i);
            if (StringUtils.isBlank(pBean.getCode())) {
                errors.add(String.format("设备装置导入第{%s}行:设备装置编号不能为空", pBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(pBean.getName())) {
                errors.add(String.format("设备装置{%s}行:设备装置名称不能为空", pBean.getRowIndex()));
                error++;
                continue;
            }
//            else if (StringUtils.isBlank(pBean.getType())) {
//                errors.add(String.format("设备装置导入第{%s}行:设备装置类型不能为空", pBean.getRowIndex()));
//                error++;
//                continue;
//            }
            else if (StringUtils.isBlank(pBean.getState())) {
                errors.add(String.format("设备装置导入第{%s}行:装置状态不能为空", pBean.getRowIndex()));
                error++;
                continue;
            }

            String errorMsg = this.checkDataAuth(pBean.getResponsibleDeptParentName(), pBean.getDepartName(), nameDeptMap, departCountMap);
            if (!StringUtils.isBlank(errorMsg)) {
                errors.add(String.format(errorMsg, "设备装置", pBean.getRowIndex()));
                error++;
                continue;
            }

            try {
                BpProductionFacility bpf = new BpProductionFacility();
                List<BpProductionFacility> bpfs = bpProductionFacilityDao.getByCode(pBean.getCode());
                if (!CollectionUtils.isEmpty(bpfs)) {
                    bpf = bpfs.get(0);
                }
                if (StringUtils.isNotBlank(pBean.getRiskDistrictCode())) {
                    if (!districtCodeMap.containsKey(pBean.getRiskDistrictCode())) {
                        errors.add(String.format("设备装置导入第{%s}行:该风险区域不在权限范围内", pBean.getRowIndex()));
                    }
                }
                if (StringUtils.isNotBlank(pBean.getMajorHazardCode())) {
                    if (!hazardCodeMap.containsKey(pBean.getMajorHazardCode())) {
                        errors.add(String.format("设备装置导入第{%s}行:该重大危险源不在权限范围内", pBean.getRowIndex()));
                    }
                }
                String mpc = pBean.getMinitorPointCodes();
                if (StringUtils.isNotBlank(mpc)) {
                    if (this.getPointCodeFlag(mpc, pointCodeMap)) {
                        errors.add(String.format("设备装置导入第{%s}行:存在监测点不在权限范围内", pBean.getRowIndex()));
                    }
                }
                BeanUtils.copyProperties(pBean, bpf);
                Long typeId = null;

                bpf.setEquipmentModel(pBean.getModelNo());
                String key = pBean.getKeyEquipment();
                if ("是".equals(key)) {
                    bpf.setKeyEquipment("Y");
                } else if ("否".equals(key)) {
                    bpf.setKeyEquipment("N");
                } else {
                    bpf.setKeyEquipment(null);
                }

                Long responsibleDeptId;
                if (departCountMap.get(pBean.getDepartName()) > 1) {
                    responsibleDeptId = this.findDeptIdByParentDeptName(deptList, pBean.getDepartName(), pBean.getResponsibleDeptParentName());
                    if (responsibleDeptId == null) {
                        error++;
                        errors.add(String.format("设备装置导入第{%s}行:部门存在多个且直属上级部门未找到", pBean.getRowIndex()));
                        continue;
                    }
                } else {
                    responsibleDeptId = nameDeptMap.get(pBean.getDepartName()).getId();
                }
                bpf.setDepartId(responsibleDeptId);
                String state = pBean.getState();
                if ("运行".equals(state)) {
                    bpf.setState(0);
                } else if ("停用".equals(state)) {
                    bpf.setState(1);
                } else {
                    errors.add(String.format("设备装置导入第{%s}行:设备装置状态不正确", pBean.getRowIndex()));
                    error++;
                    continue;
                }
                String code = pBean.getMajorHazardCode();
                Long mhId = null;
                if (null != code) {
                    bpf.setMajorHazardUnitCode(code);
                    MhMajorHazard mh = hazardCodeMap.get(code);
                    if (mh != null) {
                        bpf.setMajorHazardId(mh.getId());
                        bpf.setMajorHazardUnit(mh.getName());
                    }
                }
                bpf.setMaintenanceAmount(Double.valueOf(0));
                bpf.setRepairAmount(Double.valueOf(0));
                //所属区域编码
                if (StringUtils.isNotBlank(pBean.getRiskDistrictCode())) {
                    bpf.setRiskDistrictId(districtCodeMap.get(pBean.getRiskDistrictCode()));
                }
                //负责人编码
                if (StringUtils.isNotBlank(pBean.getPersonInChargeCode())) {
                    List<BaseUser> lbu = baseUserDao.getByCode(pBean.getPersonInChargeCode());
                    if (!CollectionUtils.isEmpty(lbu)) {
                        bpf.setPersonInChargeId(lbu.get(0).getId());
                    }
                }
                //负责人部门编码
                if (StringUtils.isNotBlank(pBean.getPicDepartCode()) && departMap.containsKey(pBean.getPicDepartCode())) {
                    bpf.setPicDepartId(departMap.get(pBean.getPicDepartCode()));
                }
                //到期日期
                if (pBean.getPutIntoUseDate() != null && pBean.getServiceLifeMonths() != null) {
                    Calendar calendar = new GregorianCalendar();
                    try {
                        calendar.setTime(DateUtil.parse(pBean.getPutIntoUseDate()));
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        errors.add(String.format("设备装置导入第{%s}行:投用日期错误", pBean.getRowIndex()));
                        continue;
                    }
                    calendar.add(Calendar.MONTH, pBean.getServiceLifeMonths());   // 单位: 月
                    bpf.setValidityDate(calendar.getTime());
                } else {
                    bpf.setValidityDate(null);
                }
                //生产日期
                if (StringUtils.isNotBlank(pBean.getManufactureDate())) {
                    try {
                        bpf.setManufactureDate(DateUtil.parse(pBean.getManufactureDate()));
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        errors.add(String.format("设备装置导入第{%s}行:生产日期错误", pBean.getRowIndex()));
                        continue;
                    }
                } else {
                    bpf.setManufactureDate(null);
                }
                //投用日期
                if (StringUtils.isNotBlank(pBean.getPutIntoUseDate())) {
                    try {
                        bpf.setPutIntoUseDate(DateUtil.parse(pBean.getPutIntoUseDate()));
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        errors.add(String.format("设备装置导入第{%s}行:投用日期错误", pBean.getRowIndex()));
                        continue;
                    }
                } else {
                    bpf.setPutIntoUseDate(null);
                }

                //是否是安全装置
                if (pBean.getSafeStatus() == null) {
                    bpf.setSafeStatus("是");
                } else {
                    bpf.setSafeStatus(pBean.getSafeStatus());
                }
                //维修状态 默认完好 1
                bpf.setRepairState(1);
                //生产装置类型
                if (StringUtils.isNotBlank(pBean.getType())) {
                    BpProductionFacilityType fType = bpProductionFacilityTypeDao.findByName(pBean.getType());
                    if (fType != null) {
                        typeId = fType.getId();
                    } else {
                        //新增
                        BpProductionFacilityType type = new BpProductionFacilityType();
                        type.setName(pBean.getType());
                        type.setParentId(0L);
                        byte a = 0;
                        type.setExpireRemindOrNot(a);
                        BpProductionFacilityType save = bpProductionFacilityTypeDao.save(type);
                        typeId = save.getId();
                    }
                    bpf.setType(typeId);
                }
                bpf = bpProductionFacilityDao.save(bpf);
                //修改生产装置类型数量
                if (typeId != null) {
                    this.updateTypeDeviceCount(typeId);
                }
                // 保存监测点信息
                List<Long> pointIds = new ArrayList<>();
                bpMonitoringPointRelDao.deleteByRefTypeAndRefId("production_facility", bpf.getId());
                if (StringUtils.isNotBlank(mpc)) {
                    String[] codes = mpc.split("\n");
                    for (int j = 0; j < codes.length; j++) {
                        // 获取监测点编码
                        String co = codes[j].trim();
                        if (StringUtils.isNotBlank(co)) {
                            if (pointCodeMap.containsKey(co)) {
                                //检查监测点是否已被关联
                                String checkResult = mhMonitoringPointService.checkMhMointPoint(pointCodeMap.get(co), bpf.getId());
                                if (StringUtils.isNotBlank(checkResult)) {
                                    errors.add(String.format("设备装置导入第{%s}行:" + checkResult, pBean.getRowIndex()));
                                    continue;
                                } else {
                                    BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                                    bpMonitoringPointRel.setRefType("production_facility");
                                    bpMonitoringPointRel.setRefId(bpf.getId());
                                    bpMonitoringPointRel.setMonitoringPointId(pointCodeMap.get(co));
                                    bpMonitoringPointRelDao.save(bpMonitoringPointRel);
                                    pointIds.add(pointCodeMap.get(co));
                                }
                            }
                        }
                    }

                }
                //将生产装置录入生产装置总表
                BpDeviceFacilityCollection facility = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(DeviceFacilityTypes.SHENG_CHAN_ZHUANG_ZHI, bpf.getId(), bpf.getCode(), bpf.getName(), null, bpf.getMajorHazardId(), bpf.getLocation());
                // 绑定监测点
                bpDeviceFacilityCollectionService.bindDeviceAndMonitorPointsByIds(facility, pointIds);
                count++;
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("设备装置导入第{%s}行:数据过长", pBean.getRowIndex()));
                log.error(e.getMessage(), e);
                error++;
                continue;
            } catch (Exception e) {
                errors.add(String.format("设备装置导入第{%s}行:数据异常", pBean.getRowIndex()));
                log.error("设备装置导入数据异常：", e);
                error++;
                continue;
            }
        }
        return returnList(errors, count, error, ignore, "设备装置");
    }


    //生产装置类型数量
    private void updateTypeDeviceCount(Long typeId) {
        if (typeId != null) {
            BpProductionFacilityType facilityType = bpProductionFacilityTypeDao.findById(typeId).get();
            List<BpProductionFacility> fList = bpProductionFacilityDao.findByType(typeId);
            if (fList != null && fList.size() > 0) {
                facilityType.setNumber(fList.size());
            } else {
                facilityType.setNumber(0);
            }
            bpProductionFacilityTypeDao.save(facilityType);
        }
    }

    private Long findMajorHazardIdByCode(String majorHazardCode) {
        MhMajorHazard mh = mhMajorHazardDao.findByCode(majorHazardCode);
        System.out.println("mh.getId()=" + mh);
        return mh == null ? null : mh.getId();
    }

    //将生产装置录入总表
    private BpDeviceFacilityCollection addOrUpdateDeviceFacilitCollection(BpProductionFacility bpf, Long typeId, Long mhId) {
        String subtype = null;
        if (typeId != null) {
            try {
                BaseTypeGroupItem one = baseTypeGroupItemDao.getOne(typeId);
                subtype = one.getName();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        BpDeviceFacilityCollection facility = deviceFacilityCollectionService.addOrUpdateProductionFacility(bpf.getId(),
                bpf.getCode(), bpf.getName(), subtype, null, mhId, bpf.getLocation(),
                bpf.getKeyEquipment());
        return facility;
    }

    /**
     * 企业基础信息导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> imporBasicInformationByExcel(MultipartFile file) {
        List<ExcelEnterpriseInfoBean> eBeans = parseData(file, 0, ExcelEnterpriseInfoBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 1; i < eBeans.size(); i++) {
            ExcelEnterpriseInfoBean eBean = eBeans.get(i);
            if (StringUtils.isBlank(eBean.getName())) {
                errors.add(String.format("企业基础信息第{%s}行:企业名称不能为空", eBean.getRowIndex()));
                error++;
                continue;
            }
            try {

                String orgCode = Context.getCompanyCode();
                Long tenantId = Context.getCurrentTenantId();
                // 判断企业信息是否已经录入
                BpEnterpriseInfo info = bpEnterpriseInfoDao.findAllByOrgCodeAndTenentId(orgCode, tenantId);
                Double peopleCount = eBean.getSurroundingPeopleCount() == null ? 0 : eBean.getSurroundingPeopleCount();
                if (peopleCount > 99999999) {
                    errors.add(String.format("企业基础信息第{%s}行:请输入8位数以内的周围暴露人数", eBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (null == info) {
                    // 不存在->保存
                    BpEnterpriseInfo bpe = new BpEnterpriseInfo();
                    bpe.setName(eBean.getName());
                    bpe.setSurroundingPeopleCount(peopleCount.intValue());
                    bpEnterpriseInfoDao.save(bpe);
                    count++;
                } else {
                    // 存在->修改
                    bpEnterpriseInfoDao.updateName(eBean.getName(), peopleCount.intValue(), info.getId());
                    //同步顶级部门名称
                    bpEnterpriseInfoService.syncDepartName(eBean.getName());
                    count++;
                }

            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("企业基础信息第{%s}行:数据过长", eBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("企业基础信息第{%s}行:数据异常", eBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "企业基础信息");
    }

    /**
     * NFC卡导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importNfcByExcel(MultipartFile file) {
        List<ExcelNfcBean> nBeans = parseData(file, 0, ExcelNfcBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < nBeans.size(); i++) {
            ExcelNfcBean nBean = nBeans.get(i);
            if (StringUtils.isBlank(nBean.getName())) {
                errors.add(String.format("NFC卡导入第{%s}行:标签名称不能为空", nBean.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtils.isBlank(nBean.getCode())) {
                errors.add(String.format("NFC卡导入第{%s}行:识别码不能为空", nBean.getRowIndex()));
                error++;
                continue;
            }
            try {
                BaseNfcCardBean baseNfcCardBean = new BaseNfcCardBean();
                BeanUtils.copyProperties(nBean, baseNfcCardBean);
                List<BPNFCLocation> nfcList = bpnfcLocationDao.findByCode(baseNfcCardBean.getCode());
                if (CollectionUtils.isEmpty(nfcList)) {
                    //1.保存
                    List<BPNFCLocation> cNameList = bpnfcLocationDao.findByName(baseNfcCardBean.getName());
                    //1.1判断名称是否已被使用
                    if (!CollectionUtils.isEmpty(cNameList)) {
                        errors.add(String.format("NFC卡导入第{%s}行:标签名称已使用", nBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    BPNFCLocation card = new BPNFCLocation();
                    card.setCode(baseNfcCardBean.getCode());
                    card.setName(baseNfcCardBean.getName());
                    bpnfcLocationDao.save(card);
                    count++;
                } else if (nfcList.size() == 1) {
                    //2.更新
                    BPNFCLocation location = nfcList.get(0);
                    if (baseNfcCardBean.getName().equals(location.getName())) {
                        //2.1更新内容与原来一样
                        bpnfcLocationDao.save(location);
                        count++;
                    } else {
                        //2.2不一样,判断 name是否已被使用
                        List<BPNFCLocation> cNameList = bpnfcLocationDao.findByName(baseNfcCardBean.getName());
                        if (!CollectionUtils.isEmpty(cNameList)) {
                            errors.add(String.format("NFC卡导入第{%s}行:标签名称已使用", nBean.getRowIndex()));
                            error++;
                            continue;
                        } else {
                            location.setName(baseNfcCardBean.getName());
                            bpnfcLocationDao.save(location);
                            count++;
                        }
                    }
                } else {
                    log.error("编码为{" + baseNfcCardBean.getCode() + "}的NFC卡有脏数据");
                }
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("NFC卡导入第{%s}行:数据过长", nBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("NFC卡导入第{%s}行:数据异常", nBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "NFC卡导入");
    }


    /**
     * 监测点导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importPointByExcel(MultipartFile file) {
        List<MonitorPointBean> pBeans = parseData(file, 0, MonitorPointBean.class, true);
        List<BpDepart> deptList = getOwnedAuthDeptCodeMapping();
        Map<String, Long> departCountMap = this.getDepartCountMap(deptList);
        Map<String, BpDepart> nameDeptMap = this.getNameDeptMap(deptList);
        int count = 0;
        int error = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        for (int i = 0; i < pBeans.size(); i++) {
            MonitorPointBean pBean = pBeans.get(i);
            if (StringUtils.isBlank(pBean.getName())) {
                errors.add(String.format("监测点{%s}行:监测点名称不能为空", pBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(pBean.getCode())) {
                errors.add(String.format("监测点{%s}行:监测点编号不能为空", pBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(pBean.getType())) {
                errors.add(String.format("监测点{%s}行:监测点类型不能为空", pBean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(pBean.getCategory())) {
                errors.add(String.format("监测点{%s}行:地图独立显示不能为空", pBean.getRowIndex()));
                error++;
                continue;
            }

            String errorMsg = this.checkDataAuth(pBean.getResponsibleDeptParentName(), pBean.getResponsibleDeptName(), nameDeptMap, departCountMap);
            if (!StringUtils.isBlank(errorMsg)) {
                errors.add(String.format(errorMsg, "监测点", pBean.getRowIndex()));
                error++;
                continue;
            }

            try {
                MhMonitoringPoint mp = new MhMonitoringPoint();
                MhMonitoringPoint p = monitoringPointDao.findByPointCode(pBean.getCode());
                if (p != null) {
                    mp = p;
                }
                mp.setName(pBean.getName());
                mp.setPointCode(pBean.getCode());
                String mType = pBean.getType();
                // 截取类型如:温度(℃),获取真正的类型"温度"和数值单位"℃"
                String sType;
                String eType;
                MhMonitoringType type = null;
                if (mType.contains("(")) {
                    sType = mType.substring(0, mType.indexOf("(")).trim();
                    eType = mType.substring(mType.indexOf("(") + 1, mType.indexOf(")")).trim();
                } else {
                    sType = mType;
                    eType = null;
                }
                //监测点分类
                Integer categoryId = null;
                if (pBean.getCategory().equals("是")) {
                    categoryId = 1;
                    if (eType == null) {
                        errors.add(String.format("监测点{%s}行:环境监测点的数值单位不能为空", pBean.getRowIndex()));
                        error++;
                        continue;
                    }
                } else if (pBean.getCategory().equals("否")) {
                    categoryId = 0;
                } else {
                    errors.add(String.format("监测点{%s}行:地图独立显示请填写正确的数值", pBean.getRowIndex()));
                    error++;
                    continue;
                }
                //获取监测点类型
                if (sType != null) {
                    if (eType != null) {
                        List<MhMonitoringType> tList = monitoringTypeDao.findByNameAndUnit(sType, eType);
                        if (!CollectionUtils.isEmpty(tList)) {
                            if (tList.get(0).getCategoryId() != null && !tList.get(0).getCategoryId().equals(categoryId.longValue())) {
                                errors.add(String.format("监测点{%s}行:该监测点类型不可在地图上显示", pBean.getRowIndex()));
                                error++;
                                continue;
                            }
                            type = tList.get(0);
                        }
                    } else {
                        List<MhMonitoringType> tList = monitoringTypeDao.findByName(sType);
                        if (!CollectionUtils.isEmpty(tList)) {
                            if (tList.get(0).getCategoryId() != null && !tList.get(0).getCategoryId().equals(categoryId.longValue())) {
                                errors.add(String.format("监测点{%s}行:该监测点类型不可在地图上显示", pBean.getRowIndex()));
                                error++;
                                continue;
                            }
                            type = tList.get(0);
                        }
                    }
                    //新增监测点类型
                    if (type == null) {
                        type = new MhMonitoringType();
                        type.setName(sType);
                        type.setUnit(eType);
                        type.setCategoryId(categoryId.longValue());
                        type.setNumber(0);
                        type.setCode(bizCodeGeneratorFacade.jiancedianleixing());
                        type = monitoringTypeDao.save(type);
                        //大屏有毒可燃气体显示
                        if (categoryId.equals(1)) {
                            workFlowProcessService.saveConfigFromMhPointType(type);
                        }
                    }
                } else {
                    errors.add(String.format("监测点{%s}行:监测点类型不能为空", pBean.getRowIndex()));
                    error++;
                    continue;
                }
                mp.setMhMonitoringType(type);
                mp.setUnit(eType);
                Double hv = parseDouble(pBean.getHighValue());
                Double lv = parseDouble(pBean.getLowValue());
                Double highValue1 = parseDouble(pBean.getLevel1a());
                Double lowValue1 = parseDouble(pBean.getLevel1b());
                Double highValue2 = parseDouble(pBean.getLevel2a());
                Double lowValue2 = parseDouble(pBean.getLevel2b());
                if (hv != null && lv != null && hv < lv) {
                    errors.add(String.format("监测点{%s}行:量程填写不正确", pBean.getRowIndex()));
                    error++;
                    continue;
                }
                Integer flag = checkPointValue(highValue1, highValue2, lowValue1, lowValue2);
                if (flag == 1) {
                    errors.add(String.format("监测点{%s}行:报警阀值填写不正确", pBean.getRowIndex()));
                    error++;
                    continue;
                }
                mp.setHighValue(pBean.getHighValue());
                mp.setLowValue(pBean.getLowValue());
                mp.setHighValue1(pBean.getLevel1a());
                mp.setLowValue1(pBean.getLevel1b());
                mp.setHighValue2(pBean.getLevel2a());
                mp.setLowValue2(pBean.getLevel2b());
                Long responsibleDeptId;
                if (departCountMap.get(pBean.getResponsibleDeptName()) > 1) {
                    responsibleDeptId = findDeptIdByParentDeptName(deptList, pBean.getResponsibleDeptName(), pBean.getResponsibleDeptParentName());
                    if (responsibleDeptId == null) {
                        error++;
                        errors.add(String.format("监测点第{%s}行:部门存在多个且直属上级部门未找到", pBean.getRowIndex()));
                        continue;
                    }
                } else {
                    responsibleDeptId = nameDeptMap.get(pBean.getResponsibleDeptName()).getId();
                }
                mp.setResponsibleDept(responsibleDeptId);
                // 默认开关开启(0关,1开)
                mp.setState(1);
                monitoringPointDao.save(mp);
                count++;
                //更改监测点类型数量
                List<MhMonitoringPoint> pList = monitoringPointDao.findByMhMonitoringType(type.getId());
                if (pList != null && pList.size() > 0) {
                    type.setNumber(pList.size());
                } else {
                    type.setNumber(0);
                }
                monitoringTypeDao.save(type);
            } catch (DataIntegrityViolationException e) {
                errors.add(String.format("监测点第{%s}行:数据过长", pBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            } catch (Exception e) {
                errors.add(String.format("监测点第{%s}行:数据异常", pBean.getRowIndex()));
                error++;
                log.error(e.getMessage(), e);
            }
        }
        return returnList(errors, count, error, ignore, "监测点");
    }

    /**
     * 解析储罐区 储罐监测点
     *
     * @param mpc
     * @param pointMap
     * @return
     */
    private List<Long> getStorePointIds(String mpc, Map<String, Long> pointMap) {
        List<Long> pointIds = new ArrayList<>();
        if (StringUtils.isNotBlank(mpc)) {
            String[] codes = mpc.split("\n");
            for (int j = 0; j < codes.length; j++) {
                // 获取监测点编码
                String co = codes[j].trim();
                if (StringUtils.isNotBlank(co)) {
                    if (pointMap.containsKey(co)) {
                        //检查监测点是否已被关联
                        pointIds.add(pointMap.get(co));
                    }
                }
            }
        }
        return pointIds;
    }


    /**
     * 读取excel数据
     *
     * @param file
     * @param sheetIndex
     * @param clazz
     * @param trimStringData
     * @param <T>
     * @return
     */
    public <T> List<T> parseData(MultipartFile file, int sheetIndex, Class<T> clazz, boolean trimStringData) {
        return parseData(file, sheetIndex, 1, clazz, trimStringData);
    }

    private <T> List<T> parseData(MultipartFile file, int sheetIndex, int startRow, Class<T> clazz,
                                  boolean trimStringData) {
        ImportParams params = new ImportParams();
        try {
            params.setStartSheetIndex(sheetIndex);
            params.setHeadRows(startRow);
            params.setTitleRows(0);
            List<T> result = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
            Iterator<T> iterator = result.iterator();
            while (iterator.hasNext()) {
                T next = iterator.next();
                Field[] fields = next.getClass().getDeclaredFields();
                //用于判断所有属性是否为空,如果参数为空则不查询
                boolean flag = false;
                for (Field field : fields) {
                    //不检查 直接取值
                    field.setAccessible(true);
                    try {
                        field.get(next);
                        if (!field.getName().equals("rowIndex") && ObjectStringUtils.isNotNull(field.get(next))) {
                            //不为空
                            flag = true;
                            //当有任何一个参数不为空的时候则跳出判断直接查询
                            break;
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
                if (!flag) {
                    iterator.remove();
                }
            }
            int index = 2;
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clazz, "rowIndex");
            if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) {
                for (T b : result) {
                    propertyDescriptor.getWriteMethod().invoke(b, params.getStartRows() + index);
                    index++;
                }
            }
            if (trimStringData) {
                for (T b : result) {
                    trimData(b);
                }
            }
            return result;
        } catch (Exception e) {
            log.error("parse data exception:", e);
        }
        return null;
    }

    private String floatToString(Float workPressureHighValue) {
        return workPressureHighValue == null ? "" : workPressureHighValue + "";
    }

    /**
     * 将has开头的文本属性转换为英文字符
     *
     * @param tank
     * @throws Exception
     */
    private void translateHasChineseToYesNo(Object tank) throws Exception {

        PropertyDescriptor[] ps = BeanUtils.getPropertyDescriptors(tank.getClass());
        for (PropertyDescriptor pd : ps) {
            if ((pd.getName().startsWith("has") || pd.getName().startsWith("is"))
                    && pd.getPropertyType() == String.class) {
                String value = BizUtils.translateChineseToYesNo((String) pd.getReadMethod().invoke(tank, null));
                pd.getWriteMethod().invoke(tank, value);
            }
        }
    }

    /**
     * 返回前端,对list进行处理
     *
     * @param errors
     * @param count
     * @param error
     * @param ignore
     * @return
     */
    private List returnList(List<String> errors, int count, int error, int ignore, String name) {
        List<String> returnList = new ArrayList<>();
        returnList.add(String.format(name + ": 成功导入%s条, 失败%s条,忽略 %s 条:", count, error, ignore));
        for (int i = 0; i < errors.size(); i++) {
            returnList.add(errors.get(i));
        }
        return returnList;
    }

    private Double parseDouble(String level1a) {
        if (StringUtils.isBlank(level1a)) {
            return null;
        }
        return Double.parseDouble(level1a);
    }

    /**
     * 监测点报警阀值校验
     *
     * @param highValue1
     * @param highValue2
     * @param lowValue1
     * @param lowValue2
     * @return
     */
    private Integer checkPointValue(Double highValue1, Double highValue2, Double lowValue1, Double lowValue2) {
        int resultFlag = 0;
        // 同低位
        if (lowValue1 != null && lowValue2 != null) {
            if (lowValue1 <= lowValue2) {
                resultFlag = 1;
            }
        }
        // 同高位
        if (resultFlag == 0 && highValue1 != null && highValue2 != null) {
            if (highValue1 >= highValue2) {
                resultFlag = 1;
            }
        }
        // 跨位
        if (resultFlag == 0 && lowValue1 != null) {
            if (highValue1 != null && lowValue1 >= highValue1) {
                resultFlag = 1;
            }
            if (resultFlag == 0 && highValue2 != null && lowValue1 >= highValue2) {
                resultFlag = 1;
            }
        }
        if (resultFlag == 0 && lowValue2 != null && lowValue1 == null) {
            if (highValue1 != null && lowValue2 >= highValue1) {
                resultFlag = 1;
            }
            if (resultFlag == 0 && highValue2 != null && lowValue2 >= highValue2) {
                resultFlag = 1;
            }
        }
        return resultFlag;
    }

    /**
     * 控制风险导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importRiskPointByExcel(MultipartFile file) {
        List<RiskDistrictControlRiskBean> jobs = parseData(file, 0, RiskDistrictControlRiskBean.class, true);
        System.out.println(jobs);
        List<DataimportValidationResult> results = DataImportValidator.batchValidate(jobs);
        if (results.size() > 0) {
            return returnList(convertToString(results), 0, results.size(), 0, "导入风险点");
        }
        int importCount = 0;
        int ignoreCount = 0;
        List<List<RiskDistrictControlRiskBean>> groups = groupRiskPointsByName(jobs);
        List<RiskDistrictControlRiskBean> rb = null;
        //从第三行数据开始，跳过第二行示例数据
        for (int i = 1; i < groups.size(); i++) {
            rb = groups.get(i);
            if ("ignore".equalsIgnoreCase(rb.get(0).getRiskPointCode())) {
                ignoreCount++;
                // 忽略某些值
                continue;
            }
            RiskPoint point = extractRiskPointInfo(rb.get(0));
            if (point != null) {
                importCount++;
                saveSclOrJhaEvaluationInfo(point, rb);
            } else {
                ignoreCount++;
            }
        }
        return returnList(convertToString(results), importCount, 0, ignoreCount, "导入风险点及评估");
    }

    private List<List<RiskDistrictControlRiskBean>> groupRiskPointsByName
            (List<RiskDistrictControlRiskBean> jobs) {
        Map<String, List<RiskDistrictControlRiskBean>> map = new LinkedHashMap<>();
        jobs.forEach(e -> {
            String key = createGroupKey(e);
            List<RiskDistrictControlRiskBean> groups = map.get(key);
            if (groups == null) {
                groups = new ArrayList<>(5);
                map.put(key, groups);
            }
            groups.add(e);
        });
        return new ArrayList<>(map.values());
    }

    private String createGroupKey(RiskDistrictControlRiskBean e) {
        return e.getRiskPointName();
    }

    /**
     * 风险点库数据导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importWorkSafetyCertRiskPointEvaluationTemplateByExcel(MultipartFile file) {
        List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean> jobs = parseData(file, 0,
                WordSafetyCertJobRiskPointJhaEvaluationRepoBean.class, true);
        List<DataimportValidationResult> results = DataImportValidator.batchValidate(jobs);
        if (results.size() > 0) {
            return returnList(convertToString(results), 0, results.size(), 0, "导入风险点数据库");
        }
        int importCount = 0;
        int ignoreCount = 0;
        List<List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean>> groups = groupSharedRiskPointsByName(jobs);
        List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean> rb = null;
        //从第三行数据开始，跳过第二行示例数据
        for (int i = 1; i < groups.size(); i++) {
            rb = groups.get(i);
            if ("ignore".equalsIgnoreCase(rb.get(0).getRiskPointCode())) {
                ignoreCount++;
                // 忽略某些值
                continue;
            }
            RiskPoint point = extractRiskPointInfo(rb.get(0));
            if (point != null) {
                importCount++;
                saveSharedSclOrJhaEvaluationInfo(point, rb);
            } else {
                ignoreCount++;
            }
        }

        return returnList(convertToString(results), importCount, 0, ignoreCount, "导入风险点及评估");
    }


    private List<List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean>> groupSharedRiskPointsByName(
            List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean> jobs) {
        Map<String, List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean>> map = new LinkedHashMap<>();
        jobs.forEach(e -> {
            String key = createGroupKey(e);
            List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean> groups = map.get(key);
            if (groups == null) {
                groups = new ArrayList<>(5);
                map.put(key, groups);
            }
            groups.add(e);
        });
        return new ArrayList<>(map.values());
    }

    private String createGroupKey(WordSafetyCertJobRiskPointJhaEvaluationRepoBean e) {
        return e.getRiskPointName();
    }

    private List<String> convertToString(List<DataimportValidationResult> results) {
        return results.stream().map(e -> {
            return String.format("第%d行，%s", e.getRowIndex(), convertErrorMap(e.getErrors()));
        }).collect(toList());
    }

    private String convertErrorMap(Map<String, String> errors) {
        StringBuilder sb = new StringBuilder();
        for (Entry<String, String> e : errors.entrySet()) {
            sb.append(e.getValue()).append(",");
        }
        return sb.toString();
    }

    private void trimData(Object rb) {
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(rb.getClass());
        for (PropertyDescriptor pd : descriptors) {
            if (pd.getPropertyType() == String.class && pd.getWriteMethod() != null && pd.getReadMethod() != null) {
                try {
                    String value = (String) pd.getReadMethod().invoke(rb, null);
                    if (value != null) {
                        value = value.trim();
                        pd.getWriteMethod().invoke(rb, value);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveSclOrJhaEvaluationInfo(RiskPoint point, List<RiskDistrictControlRiskBean> rb) {
        RiskPointTypes type = RiskPointTypes.findByCode(point.getType());
        if (type == RiskPointTypes.JOB_ACTIVITY) {
            saveJhaEvaluation(point, rb);
        } else if (type == RiskPointTypes.DEVICE_FACILITY) {
            saveJhaEvaluation(point, rb);
            // TODO 待开发，暂时无此需求
        }
    }

    private void saveJhaEvaluation(RiskPoint point, List<RiskDistrictControlRiskBean> rb) {
        RiskJhaEvaluationBean bean = new RiskJhaEvaluationBean();
        bean.setAnalyzeTime(parseAnalyzeTime(rb.get(0).getAnalyzeTime()));
        bean.setAnalyzeUserId(parseAnanlyzeUserId(rb.get(0).getAnalyzeUser()));
        bean.setJobId(parseAnalyzeJobId(rb.get(0).getAnalyzeUserJob()));
        // bean.setJobActivity(rb.get(0).getJobStep());
        List<RiskPointEvaluationJhaItem> items = new ArrayList<>(rb.size());
        RiskPointEvaluationJhaItem item = null;
        StringBuffer riskSources = new StringBuffer();
        for (RiskDistrictControlRiskBean b : rb) {
            item = parseJhaItem(b);
            items.add(item);
            if (item.getRiskSource() != null) {
                riskSources.append(item.getRiskSource());
            }
        }
        bean.setItems(items);
        bean.setRiskLevel(findRiskLevels(items));
        bean.setRiskSources(riskSources.toString());

        // riskPointEvaluationJhaService.doEvaluation(point, bean);
        bean.setId(point.getId());
        riskPointService.doJhaEvaluation(bean);
    }

    private RiskPointEvaluationJhaItem parseJhaItem(RiskDistrictControlRiskBean rb) {
        RiskPointEvaluationJhaItem item = new RiskPointEvaluationJhaItem();
        item.setCheckItem(rb.getJobStep());
        item.setConsequence(rb.getAccidentTypeAndConsequence());
        item.setControlMethodEmegency(rb.getEmergencyMethod());
        item.setControlMethodManage(rb.getManageMethod());
        item.setControlMethodProtect(rb.getProtectMethod());
        item.setControlMethodTech(rb.getTechMethod());
        item.setControlMethodTrain(rb.getEducationMethod());
        item.setRiskSource(rb.getRiskSourceOrPotentialEvent());

        item.setLikehood(safeParseFloat(rb.getL()));
        item.setExposure(safeParseFloat(rb.getE()));

        item.setConsequenceLevel(calculateConsequenceLevel(rb.getC()));
        // C 值有前缀，不能直接相乘
        float d = item.getLikehood() * item.getExposure() * safeParseFloat(rb.getC());
        item.setDanger(d);
        // <70 低风险
        // 70～159 一般风险
        // 160～319 较大风险
        // >320 重大风险
        if (d < 70) {
            item.setRiskLevel(RiskLevels.DI_FENG_XIAN.getCode());
        } else if (d < 160) {
            item.setRiskLevel(RiskLevels.YI_BAN_FENG_XIAN.getCode());
        } else if (d < 319) {
            item.setRiskLevel(RiskLevels.JIAO_DA_FENG_XIAN.getCode());
        } else {
            item.setRiskLevel(RiskLevels.ZHONG_DA_FENG_XIAN.getCode());
        }
        // item.setDanger(safeParseFloat(rb.getD()));
        // item.setRiskLevel(parseRiskLevel(rb));

        return item;
    }

    private Float calculateConsequenceLevel(String c) {
        if (c == null) {
            return 11f;
        }
        // 添加的1 表示严重性类型。
        // 1 : 法律法规及其他要求
        // 2 : 人员伤亡
        // 3 : 直接经济损失（万元）
        // 4 : 停工
        // 5 : 公司形象
        // 6 发生事故产生的后果
        return Float.parseFloat("6" + c);
    }

    private void saveSharedSclOrJhaEvaluationInfo(RiskPoint point,
                                                  List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean> rb) {
        RiskPointTypes type = RiskPointTypes.findByCode(point.getType());
        if (type == RiskPointTypes.JOB_ACTIVITY) {
            saveSharedJhaEvaluation(point, rb);
        } else if (type == RiskPointTypes.DEVICE_FACILITY) {
            saveSharedJhaEvaluation(point, rb);
            // TODO 待开发，暂时无此需求
        }
    }

    private void saveSharedJhaEvaluation(RiskPoint
                                                 point, List<WordSafetyCertJobRiskPointJhaEvaluationRepoBean> rb) {
        RiskJhaEvaluationBean bean = new RiskJhaEvaluationBean();
        bean.setAnalyzeTime(parseAnalyzeTime(rb.get(0).getAnalyzeTime()));
        bean.setAnalyzeUserId(parseAnanlyzeUserId(rb.get(0).getAnalyzeUser()));
        bean.setJobId(parseAnalyzeJobId(rb.get(0).getAnalyzeUserJob()));
        bean.setJobActivity(rb.get(0).getJobStep());
        List<RiskPointEvaluationJhaItem> items = new ArrayList<>(rb.size());
        StringBuffer riskResources = new StringBuffer();
        RiskPointEvaluationJhaItem item = null;
        for (WordSafetyCertJobRiskPointJhaEvaluationRepoBean b : rb) {
            item = parseJhaItem(b);
            items.add(item);
            if (item.getRiskSource() != null) {
                riskResources.append(item.getRiskSource());
            }
        }
        bean.setItems(items);
        bean.setRiskLevel(findRiskLevels(items));
        bean.setRiskSources(riskResources.toString());
        // 导入的是模板
        bean.setTemplate(true);
        // riskPointEvaluationJhaService.doEvaluation(point, bean);
        bean.setId(point.getId());
        riskPointService.doJhaEvaluation(bean);
    }

    private Integer findRiskLevels(List<RiskPointEvaluationJhaItem> items) {
        Integer level = Integer.MAX_VALUE;
        for (RiskPointEvaluationJhaItem item : items) {
            if (item.getRiskLevel() != null && item.getRiskLevel() < level) {
                level = item.getRiskLevel();
            }
        }
        return level == Integer.MAX_VALUE ? null : level;
    }

    private RiskPointEvaluationJhaItem parseJhaItem(WordSafetyCertJobRiskPointJhaEvaluationRepoBean rb) {

        // System.out.println(ToStringBuilder.reflectionToString(rb));

        RiskPointEvaluationJhaItem item = new RiskPointEvaluationJhaItem();
        item.setCheckItem(rb.getJobStep());
        item.setConsequence(rb.getAccidentTypeAndConsequence());
        item.setControlMethodEmegency(rb.getEmergencyMethod());
        item.setControlMethodManage(rb.getManageMethod());
        item.setControlMethodProtect(rb.getProtectMethod());
        item.setControlMethodTech(rb.getTechMethod());
        item.setControlMethodTrain(rb.getEducationMethod());
        item.setRiskSource(rb.getRiskSourceOrPotentialEvent());


        if (StringUtils.isNotEmpty(rb.getL())) {
            item.setLikehood(safeParseFloat(rb.getL()));
        } else {
            item.setLikehood(1f);
        }
        if (StringUtils.isNotEmpty(rb.getE())) {
            item.setExposure(safeParseFloat(rb.getE()));
        } else {
            item.setExposure(1f);
        }
        if (StringUtils.isNotEmpty(rb.getC())) {
            item.setConsequenceLevel(calculateConsequenceLevel(rb.getC()));
        } else {
            item.setConsequenceLevel(1f);
        }

        float d = item.getLikehood() * item.getExposure() * safeParseFloat(rb.getC());
        item.setDanger(d);
        // <70 低风险
        // 70～159 一般风险
        // 160～319 较大风险
        // >320 重大风险
        if (d < 70) {
            item.setRiskLevel(RiskLevels.DI_FENG_XIAN.getCode());
        } else if (d < 160) {
            item.setRiskLevel(RiskLevels.YI_BAN_FENG_XIAN.getCode());
        } else if (d < 319) {
            item.setRiskLevel(RiskLevels.JIAO_DA_FENG_XIAN.getCode());
        } else {
            item.setRiskLevel(RiskLevels.ZHONG_DA_FENG_XIAN.getCode());
        }

        return item;
    }

    // 思考后，还是采用严格模式，数据类型不对就报错，要求用户输入高质量的数据，可以减少系统内部潜在的问题
    private Integer safeParseInteger(String c) {
        return Integer.parseInt(c);
    }

    private Float safeParseFloat(String value) {
        if (StringUtils.isEmpty(value)) {
            return 1f;
        }
        return Float.parseFloat(value);
    }

    private Integer parseRiskLevel(RiskDistrictControlRiskBean rb) {
        RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel());
        return riskLevels == null ? null : riskLevels.getCode();
    }

    private Long parseAnalyzeJobId(String analyzeUserJob) {
        if (StringUtils.isNotBlank(analyzeUserJob)) {
            BpJob job = bpJobDao.findByName(analyzeUserJob);
            return job == null ? null : job.getId();
        }
        return null;
    }

    private Long parseAnanlyzeUserId(String analyzeUser) {
        if (StringUtils.isNotBlank(analyzeUser)) {
            BaseUser user = baseUserDao.findFirstByRealName(analyzeUser);
            return user == null ? null : user.getId();
        }
        return null;
    }

    private Date parseAnalyzeTime(String time) {
        if (StringUtils.isNotBlank(time)) {
            try {
                return SimpleDateFormatCache.getFormat("yyyy年M月d日").parse(time);
            } catch (Exception e) {
            }
        }
        return new Date();
    }

    private RiskPoint extractRiskPointInfo(RiskDistrictControlRiskBean rb) {
        List<RiskDistrict> riskDistricts = riskDistrictDao.findByCode(rb.getRiskDistrictCode());
        if (org.springframework.util.CollectionUtils.isEmpty(riskDistricts)) {
            log.warn("风险点: 第" + rb.getRowIndex() + "行，风险分析对象编号不存在,忽略此条数据。" + rb.getRiskPointName());
            return null;
        }
        RiskDistrict riskDistrict = riskDistricts.get(0);
        RiskPoint point = riskPointDao.findFirstByNameAndSharedIsNull(rb.getRiskPointName());
        if (point != null) {
            // 已经存在，则不重复导入
            return null;
        }
        point = new RiskPoint();
        point.setName(rb.getRiskPointName());
        if (StringUtils.isNotBlank(rb.getRiskPointCode())) {
            point.setCode(rb.getRiskPointCode());
        } else {
            point.setCode(bizCodeGeneratorFacade.fengXianDian());
        }
        point.setState(0);
        RiskPointTypes types = RiskPointTypes.findByName(rb.getRiskPointType());
        if (types != null) {
            point.setType(types.getCode());

            if (types == RiskPointTypes.DEVICE_FACILITY) {
                RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel2());
                point.setRiskLevel(riskLevels == null ? null : riskLevels.getCode());
            } else if (types == RiskPointTypes.JOB_ACTIVITY) {
                RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel());
                point.setRiskLevel(riskLevels == null ? null : riskLevels.getCode());
            }
        }

        point.setRiskDistrict(riskDistrict);
        point.setStandard(rb.getStandard());
        point.setUnstandardSituationConsequence(rb.getUnstandardSituationAndConsequence());
        point.setAccidentType(rb.getAccidentTypeAndConsequence());
        point.setDescription(rb.getRiskSourceOrPotentialEvent());

        point.setResponsibleDepart(findRiskPointResponsibleDepart(rb));
        point.setResponsibleUser(findRiskPointResponsibleUser(rb));
        ControlLevels controlLevels = ControlLevels.findControlLevelByName(rb.getControlLevel());

        if (controlLevels != null) {
            point.setControlLevelId((long) controlLevels.getCode());
        }
        riskPointDao.save(point);
        return point;
    }

    private RiskPoint extractRiskPointInfo(WordSafetyCertJobRiskPointJhaEvaluationRepoBean rb) {
        RiskPoint point = riskPointDao.findFirstByNameAndShared(rb.getRiskPointName(), 1);
        if (point != null) {
            // 已经存在，则不重复导入
            return null;
        }
        point = new RiskPoint();
        point.setName(rb.getRiskPointName());
        // 设置为共享的,专门用于作业证相关
        point.setShared(1);
        if (StringUtils.isNotBlank(rb.getRiskPointCode())) {
            point.setCode(rb.getRiskPointCode());
        } else {
            point.setCode(bizCodeGeneratorFacade.fengXianDian());
        }
        point.setState(0);
        RiskPointTypes types = RiskPointTypes.findByName(rb.getRiskPointType());
        if (types != null) {
            point.setType(types.getCode());

            if (types == RiskPointTypes.DEVICE_FACILITY) {
                RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel2());
                point.setRiskLevel(riskLevels == null ? null : riskLevels.getCode());
            } else if (types == RiskPointTypes.JOB_ACTIVITY) {
                RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel());
                point.setRiskLevel(riskLevels == null ? null : riskLevels.getCode());
            }
        }

        point.setStandard(rb.getStandard());
        point.setUnstandardSituationConsequence(rb.getRiskSourceOrPotentialEvent());
        point.setAccidentType(rb.getAccidentTypeAndConsequence());
        point.setDescription(rb.getRiskSourceOrPotentialEvent());

        riskPointDao.save(point);
        return point;
    }

    private BaseUser findRiskPointResponsibleUser(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getResponsibleUserCode())) {
            return baseUserDao.findByCode(rb.getResponsibleUserCode());
        } else if (StringUtils.isNotBlank(rb.getResponsibleUser())) {
            return baseUserDao.findFirstByRealName(rb.getResponsibleUser());
        }
        return null;
    }

    private BpDepart findRiskPointResponsibleDepart(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getResponsibleDepartCode())) {
            return bpDepartDao.findFirstByCode(rb.getResponsibleDepartCode());
        } else if (StringUtils.isNotBlank(rb.getResponsibleDepart())) {
            return bpDepartDao.findFirstByName(rb.getResponsibleDepart());
        }
        return null;
    }


    /**
     * 固定风险评估导入
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importRiskDistrictStableByExcel(MultipartFile file) {
        List<RiskDistrictStableRiskBean> list = parseData(file, 0, RiskDistrictStableRiskBean.class, true);
       /* List<DataimportValidationResult> validations = DataImportValidator.batchValidate(list);
        if (!validations.isEmpty()) {
            return returnList(convertToString(validations), 0, 0, 0, "导入风险区域及固定风险评估");
        }*/
        int errorCount = 0;
        int ignoreCount = 0;
        int successCount = 0;
        List<String> errors = new ArrayList<>();
        RiskDistrictStableRiskBean rb = null;
        for (int i = 1; i < list.size(); i++) {
            rb = list.get(i);
            if (StringUtils.isBlank(rb.getName())) {
                errorCount++;
                errors.add(String.format("风险区域第{%s}行:风险区域名称不能为空", rb.getRowIndex()));
                continue;

            }
            try {
                RiskDistrict entity = riskDistrictDao.findFirstByName(rb.getName());
                if (entity == null) {
                    entity = new RiskDistrict();
                    if (StringUtils.isNotEmpty(rb.getCode())) {
                        entity.setCode(rb.getCode().trim());
                    }
                    entity.setName(rb.getName());
                    riskDistrictDao.save(entity);

                    RiskDistrictEvaluation evaluation = new RiskDistrictEvaluation();
                    evaluation.setRiskDistrictId(entity.getId());
                    evaluation.setEffective(1);
                    Long idByName = bpDepartDao.findIdByName(rb.getEvaluationOffice());
                    if (idByName != null) {
                        evaluation.setEvaluationOffice(idByName.toString());
                    }
                    evaluation.setEvaluationTime(parseStateRiskEvaluationTime(rb.getEvaluationTime()));
                    evaluation.setEvaluationUserId(findUserIdByName(rb.getEvaluationUser()));
                    evaluation.setStableRiskL(rb.getL());
                    evaluation.setStableRiskS(rb.getS());
                    evaluation.setStableRiskLevel(calculateStableRiskLevel(rb));
                    evaluation.setRiskLevel(evaluation.getStableRiskLevel());
                    riskDistrictEvaluationService.add(evaluation);
                    successCount++;
                } else {
                    errors.add(String.format("风险区域第{%s}行:风险区域已存在", rb.getRowIndex()));
                    ignoreCount++;
                    continue;
                }

            } catch (Exception e) {
                errorCount++;
                errors.add(String.format("第%d行，导入错误:%s", list.indexOf(rb) + 1, e.getMessage()));
                e.printStackTrace();
            }
        }
        return returnList(errors, successCount, errorCount, ignoreCount, "导入风险区域及固定风险评估");
    }

    /**
     * 标准排查库
     *
     * @param file
     * @return
     */

    @Override
    public ResultBean importInvestigateData(MultipartFile file) {
        List<BpInvestigateStoreExcelBean> list = parseData(file, 0, BpInvestigateStoreExcelBean.class, true);
        List<String> errors = new ArrayList<>();
        int errorCount = 0;
        int successCount = 0;
        List<BpInvestigateStore> allStoreList = storeRepository.findAll();

        //数据处理
        for (int i = 1; i < list.size(); i++) {
            BpInvestigateStoreExcelBean bean = list.get(i);
            //判断非空，内容长度
            String content = bean.getContent();
            if (org.apache.commons.lang3.StringUtils.isBlank(content)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,排查内容不能为空");
                continue;
            }
            String accordance = bean.getAccordance();
            if (org.apache.commons.lang3.StringUtils.isBlank(accordance)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,排查依据不能为空 ");
                continue;
            }
            String curStore = bean.getCurStore();
            if (org.apache.commons.lang3.StringUtils.isBlank(curStore)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,当前标准库不能为空");
                continue;
            }
            String parentStore = bean.getParentStore();
            if (org.apache.commons.lang3.StringUtils.isBlank(parentStore)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,上级标准库不能为空");
                continue;
            }
            String grandStore = bean.getGrandStore();
            if (org.apache.commons.lang3.StringUtils.isBlank(grandStore)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,上上级标准库不能为空");
                continue;
            }

            try {
                //上上级
                Map<String, Long> grandMap = allStoreList.stream().filter(r -> r.getParentId() == 0)
                        .collect(Collectors.toMap(r -> r.getCheckTypeName(), r -> r.getId()));
                Long grandId;
                if (grandMap.containsKey(grandStore)) {
                    grandId = grandMap.get(grandStore);
                } else {
                    BpInvestigateStore bpInvestigateStore = new BpInvestigateStore(grandStore, 0L, false);
                    BpInvestigateStore save = storeRepository.save(bpInvestigateStore);
                    allStoreList.add(save);
                    grandId = save.getId();
                }
                //上级
                Map<String, Long> parentMap = allStoreList.stream().filter(r -> r.getParentId().equals(grandId))
                        .collect(Collectors.toMap(r -> r.getCheckTypeName(), r -> r.getId()));
                Long parentId;
                if (parentMap.containsKey(parentStore)) {
                    parentId = parentMap.get(parentStore);
                } else {
                    BpInvestigateStore bpInvestigateStore = new BpInvestigateStore(parentStore, grandId, false);
                    BpInvestigateStore save = storeRepository.save(bpInvestigateStore);
                    allStoreList.add(save);
                    parentId = save.getId();
                }
                //当前级
                final Long parentTempId = parentId;
                Map<String, Long> curMap = allStoreList.stream().filter(r -> r.getParentId().equals(parentTempId))
                        .collect(Collectors.toMap(r -> r.getCheckTypeName(), r -> r.getId()));
                Long curId;
                if (curMap.containsKey(curStore)) {
                    curId = curMap.get(curStore);
                } else {
                    BpInvestigateStore bpInvestigateStore = new BpInvestigateStore(curStore, parentId, true);
                    BpInvestigateStore save = storeRepository.save(bpInvestigateStore);
                    allStoreList.add(save);
                    curId = save.getId();
                }
                BpInvestigateStoreDetail storeDetail = new BpInvestigateStoreDetail(curId, curStore, content, accordance);
                detailRepository.save(storeDetail);
                successCount++;
            } catch (DataIntegrityViolationException e) {
                log.error(e.getMessage(), e);
                errorCount++;
                errors.add("第" + (i + 3) + "行,数据过长");
                continue;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                errorCount++;
                errors.add("第" + (i + 3) + "行,数据异常");
                continue;
            }
        }
        return ResultBean.success(returnList(errors, successCount, errorCount, 0, "隐患标准库"));
    }

    /**
     * 隐患排查表
     *
     * @param file
     * @return
     */
    @Override
    public BpSafeTableExcelReturnBean importSafeTableData(MultipartFile file) {
        List<BpSafeTableExcelBean> list = parseData(file, 0, BpSafeTableExcelBean.class, true);
        BpSafeTableExcelReturnBean eB = new BpSafeTableExcelReturnBean();
        int errorCount = 0;
        int successCount = 0;
        int ignore = 0;
        List<String> errors = new ArrayList<>();
        List<BpSafeTableExcelBean> returnList = new ArrayList<>();
        Map<String, BpSafeTableExcelBean> map = new HashMap<>();
        for (int i = 1; i < list.size(); i++) {
            BpSafeTableExcelBean bean = list.get(i);
            String item = bean.getItem();
            String content = bean.getContent();
            String standard = bean.getStandard();
            if (StringUtils.isBlank(item)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,排查项目不能为空");
                continue;
            }

            if (StringUtils.isBlank(content)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,排查内容不能为空");
                continue;
            }
            if (item.length() > 512 || content.length() > 512 || (StringUtils.isNotBlank(standard) && standard.length() > 512)) {
                errorCount++;
                errors.add("第" + (i + 3) + "行,隐患排查表数据过长");
                continue;
            }
            String key = item + "-" + content + "-" + bean.getStandard();

            //三项内容一样 则去重
            if (map.keySet() != null && map.keySet().size() > 0) {
                if (map.get(key) != null) {
                    ignore++;
                    errors.add("第" + (i + 3) + "行,数据重复");
                    continue;
                }
            }
            map.put(key, bean);
            returnList.add(bean);
            successCount++;
        }
        errors = returnList(errors, successCount, errorCount, ignore, "安全排查表");
        eB.setErrors(errors);
        eB.setList(returnList);
        return eB;
    }

    @Override
    public List<String> importCertificateByExcel(MultipartFile file) {
        List<WwytUedCertificateImportBean> certs = parseData(file, 0, WwytUedCertificateImportBean.class, true);
        List<String> errors = new ArrayList<>();
        int count = 0;
        int error = 0;
        int ignore = 0;
        for (int i = 0; i < certs.size(); i++) {
            WwytUedCertificateImportBean cert = certs.get(i);
            if (StringUtil.isEmpty(cert.getUserCode())) {
                errors.add(String.format("第{%s}行:工号不能为空", cert.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtil.isEmpty(cert.getUserName())) {
                errors.add(String.format("第{%s}行:姓名不能为空", cert.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtil.isEmpty(cert.getPeopleType())) {
                errors.add(String.format("第{%s}行:人员类型不能为空", cert.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtil.isEmpty(cert.getCertificateName())) {
                errors.add(String.format("第{%s}行:证书种类名称不能为空", cert.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtil.isEmpty(cert.getCertNo())) {
                errors.add(String.format("第{%s}行:证书编号不能为空", cert.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtil.isEmpty(cert.getCertificateStatus())) {
                errors.add(String.format("第{%s}行:状态不能为空", cert.getRowIndex()));
                error++;
                continue;
            }
            if (StringUtil.notEmpty(cert.getUserName()) && StringUtil.notEmpty(cert.getUserCode()) && StringUtil.notEmpty(cert.getPeopleType())) {
                if (cert.getPeopleType().equals("否")) {
                    BaseUser user = baseUserDao.findByRealNameAndCode(cert.getUserName(), cert.getUserCode());
                    if (user == null) {
                        errors.add(String.format("第{%s}行:通过工号和姓名查询不到本公司人员", cert.getRowIndex()));
                        error++;
                        continue;
                    }
                } else if (cert.getPeopleType().equals("是")) {
                    BpContractorStaff staff = bpContractorStaffDao.findByNameAndCode(cert.getUserName(), cert.getUserCode());
                    if (staff == null) {
                        errors.add(String.format("第{%s}行:通过工号和姓名查询不到承包商人员", cert.getRowIndex()));
                        error++;
                        continue;
                    } else {
                        Optional<BpContractor> obc = bpContractorDao.findById(staff.getContractorId());
                        if (obc.isPresent() && StringUtils.isNotBlank(obc.get().getContractorType()) && !obc.get().getContractorType().equals("合格承包商")) {
                            errors.add(String.format("第{%s}行:请选择合格承包商人员", cert.getRowIndex()));
                            error++;
                            continue;
                        }
                    }
                }
            }

            WwytEduCertificate certificate = wwytEduCertificateService.selectByCertificateName(cert.getCertificateName());
            if (certificate == null) {
                errors.add(String.format("第{%s}行:证书种类不存在", cert.getRowIndex()));
                error++;
                continue;
            }

            String st = cert.getCertificateStatus();
            if (StringUtil.notEmpty(st)) {
                if (!st.equals("草稿") && !st.equals("归档") && !st.equals("作废")) {
                    errors.add(String.format("第{%s}行:状态种类不存在", cert.getRowIndex()));
                    error++;
                    continue;
                }
            }
            if (cert.getTakenTime() != null && cert.getOutOfDateTime() != null && cert.getOutOfDateTime().before(cert.getTakenTime())) {
                errors.add(String.format("第{%s}行:有效期结束时间早于有效期开始时间", cert.getRowIndex()));
                error++;
                continue;
            }
            WwytEduCertificateUser wecu = new WwytEduCertificateUser();
            BeanUtils.copyProperties(cert, wecu);
            //状态
            String cs = cert.getCertificateStatus();
            if (cs.equals("草稿")) {
                wecu.setCertificateStatus(0);
            }
            if (cs.equals("归档")) {
                wecu.setCertificateStatus(1);
            }
            if (cs.equals("作废")) {
                wecu.setCertificateStatus(2);
            }
            //确定哪个人
            Long userId = null;
            if (cert.getPeopleType().equals("否")) {
                wecu.setUserContractorFlag(false);
                BaseUser user = baseUserDao.findByRealNameAndCode(cert.getUserName(), cert.getUserCode());
                if (user != null) {
                    userId = user.getId();
                }
            } else if (cert.getPeopleType().equals("是")) {
                wecu.setUserContractorFlag(true);
                BpContractorStaff staff = bpContractorStaffDao.findByNameAndCode(cert.getUserName(), cert.getUserCode());
                if (staff != null) {
                    userId = staff.getId();
                }
            }
            wecu.setUserId(userId);
            //用userId和证书种类证书编号确定是否是更新操作
            wecu.setCertId(certificate.getId());
            WwytEduCertificateUser exist = wwytEduCertificateUserService.checkNeedUpdate(userId, wecu.getUserContractorFlag(), certificate.getId(), cert.getCertNo());

            if (exist != null) {
                wecu.setId(exist.getId());
                LambdaQueryWrapper<WwytEduCertificateUser> repeat = new QueryWrapper<WwytEduCertificateUser>().lambda()
                        .ne(WwytEduCertificateUser::getId, exist.getId())
                        .eq(WwytEduCertificateUser::getCertId, certificate.getId())
                        .eq(WwytEduCertificateUser::getCertNo, cert.getCertNo());
                List<WwytEduCertificateUser> list = wwytEduCertificateUserService.list(repeat);
                if (cn.zlg.common.util.CollectionUtils.isNotEmpty(list)) {
                    errors.add(String.format("第{%s}行:证书编号重复, 一个证书种类的只能有一个唯一编号", cert.getRowIndex()));
                    error++;
                    continue;
                }
            } else {
                LambdaQueryWrapper<WwytEduCertificateUser> repeat = new QueryWrapper<WwytEduCertificateUser>().lambda()
                        .eq(WwytEduCertificateUser::getCertId, certificate.getId())
                        .eq(WwytEduCertificateUser::getCertNo, cert.getCertNo());
                Integer number = wwytEduCertificateUserMapper.selectCount(repeat);
                if (number > 0) {
                    errors.add(String.format("第{%s}行:证书编号重复, 一个证书种类的只能有一个唯一编号", cert.getRowIndex()));
                    error++;
                    continue;
                }
            }
            wecu.setUpdateTime(new Date());
            wecu.setUpdateBy(Context.getCurrentUserId());
            wwytEduCertificateUserService.saveOrUpdate(wecu);
            count++;

        }
        return returnList(errors, count, error, ignore, "持证管理");
    }

    private Map<String, Long> getDepartCountMap(List<BpDepart> deptList) {
        return deptList.stream().collect(Collectors.groupingBy(BpDepart::getName, Collectors.counting()));
    }

    private Map<String, BpDepart> getNameDeptMap(List<BpDepart> deptList) {
        return deptList.stream().collect(Collectors.toMap(BpDepart::getName, Function.identity(), (k1, k2) -> k1));
    }


    @Override
    public List<BpDepart> getOwnedAuthDeptCodeMapping() {
        List<Long> deptIds = dataAuthService.findDepartIdsByCurUser();
        return bpDepartDao.findCodeListByDeptIds(deptIds);
    }

    private Long findDeptIdByParentDeptName(List<BpDepart> deptList, String responsibleDeptName, String
            responsibleDeptParentName) {
        Long parentId = bpDepartDao.findIdByName(responsibleDeptParentName);
        if (parentId != null) {
            Optional<Long> optionalId = deptList.stream().filter(each -> parentId.equals(each.getParentId()) && responsibleDeptName.equals(each.getName())).findFirst().map(BpDepart::getId);
            return optionalId.orElse(null);
        }
        return null;
    }

    private Map<String, MhMajorHazard> getHazardCodeMap() {
        List<MhMajorHazard> mhMajorHazards = mhMajorHazardService.findByResponsibleDept();
        return mhMajorHazards.stream().collect(Collectors.toMap(MhMajorHazard::getCode, Function.identity(), (k1, k2) -> k2));
    }

    private Map<String, Long> getPointCodeMap() {
        List<MhMonitoringPoint> points = mhMonitoringPointService.findByResponsibleDept();
        return points.stream().collect(Collectors.toMap(MhMonitoringPoint::getPointCode, MhMonitoringPoint::getId, (k1, k2) -> k2));

    }

    private String checkDataAuth(final String deptParentName, final String deptName, Map<
            String, BpDepart> nameDeptMap, Map<String, Long> departCountMap) {
        if (StringUtils.isBlank(deptName)) {
            return "%s导入第{%s}行:责任部门名称不能为空";
        }
        if (!nameDeptMap.containsKey(deptName)) {
            return "%s导入第{%s}行:责任部门不在权限范围内";
        }
        if (departCountMap.get(deptName) > 1 && StringUtils.isBlank(deptParentName)) {
            return "%s导入第{%s}行:责任部门名称存在多个，请填写上级责任部门名称";
        }
        return null;
    }

    private boolean getPointCodeFlag(String mpc, Map<String, Long> pointCodeMap) {
        String[] codes = mpc.split("\n");
        boolean flag = false;
        for (String code : codes) {
            // 获取监测点编码
            if (!pointCodeMap.containsKey(code.trim())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    private Date parseStateRiskEvaluationTime(String evaluationTime) {
        try {
            return SimpleDateFormatCache.getYmd().parse(evaluationTime);
        } catch (Exception e) {
        }
        return null;
    }

    private Long findUserIdByName(String evaluationUser) {
        BaseUser user = baseUserDao.findFirstByRealName(evaluationUser);
        return user == null ? null : user.getId();
    }

    private Integer calculateStableRiskLevel(RiskDistrictStableRiskBean rb) {
        int l = StringUtils.isEmpty(rb.getL()) ? 0 : Integer.parseInt(rb.getL());
        int s = StringUtils.isEmpty(rb.getS()) ? 0 : Integer.parseInt(rb.getS());
        int r = l * s;
        if (r < 4) {
            return 4;
        } else if (r < 8) {
            return 3;
        } else if (r < 10) {
            return 2;
        } else {
            return 1;
        }
    }

    private Map<String, Long> getGroutItemMap(String type) {
        Map<String, Long> map = new HashMap<>();
        BaseTypeGroup m = baseTypeGroupDao.findByName(type);
        if (m != null) {
            List<BaseTypeGroupItem> all = baseTypeGroupItemDao.findByTypeGroupId(m.getId());
            for (BaseTypeGroupItem item : all) {
                map.put(item.getName(), item.getId());
            }
        }
        return map;
    }

    private boolean isEmployeeSyncOpen() {
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_EMPLOYEE_SYNC_OPEN);
        return config == null ? false : "true".equalsIgnoreCase(config.getValue());
    }

    private boolean isVersionOpen() {
        boolean flag = false;
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_VERSION);
        if (config != null && config.getValue().equals("4.x")) {
            flag = true;
        }
        return flag;
    }

    /**
     * 查询导入的报警模板名称是否存在
     *
     * @param name
     * @return
     */
    private Integer findAlarmTemplate(String name) {
        OrientationSearchBean searchBean = new OrientationSearchBean();
        searchBean.setTemplateName(name);
        searchBean.setPage(0);
        searchBean.setSize(15);
        ResultBean resultBean = null;
        Integer alarmTemplateId = null;
        try {
            resultBean = orientationDataSyncService.alarmTemplate(searchBean);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("报警模板查询失败");
        }
        if (null != resultBean) {
            if (0 != resultBean.getLength()) {
                Object data = resultBean.getData();
                List<Map<String, Object>> dateList = (List<Map<String, Object>>) data;
                for (Map<String, Object> map : dateList) {
                    String alarmTemplateName = (String) map.get("name");
                    if (name.equals(alarmTemplateName)) {
                        Map<String, Object> dateMap = dateList.get(0);
                        alarmTemplateId = (Integer) dateMap.get("id");
                        break;
                    }
                }
            }
        } else {
            throw new IllegalArgumentException("报警模板查询失败");
        }
        return alarmTemplateId;
    }

    private Boolean getAlarmSwitch() {
        BaseConfig config = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(), BaseConfigCodes.LOCATE_SERVICE_ALARM_OPEN);
        return config == null || StringUtils.isBlank(config.getValue()) || config.getValue().trim().equals("true");
    }


    /*@Override
    public CheckItemBean importCheckItem(MultipartFile file) {
        List<ExcelCheckItemBean> checkItemBeans = parseData(file, 0, 2, ExcelCheckItemBean.class, true);
        int count = 0;
        int error = 0;
        int ignore = 0;
        CheckItemBean checkItemBean = new CheckItemBean();
        List<String> errors = new ArrayList<>();
        //返回的列表
        List list = new ArrayList();
        if (CollectionUtils.isEmpty(checkItemBeans)){
            errors.add("未解析到数据");
            return checkItemBean;
        }
        List<CheckItemDetailVo> checkItemDetailVoList = new ArrayList<>();
        for (int i = 0; i < checkItemBeans.size(); i++) {
            //检查项目
            CheckItemDetailVo  checkItemDetailVo = new CheckItemDetailVo();

            ExcelCheckItemBean itemBean = checkItemBeans.get(i);
            if (StringUtils.isBlank(itemBean.getDeviceCode())){
                errors.add(String.format("第{%s}行:设备编号不能为空",itemBean.getRowIndex()));
                error++;
                continue;
            }else if (StringUtils.isBlank(itemBean.getCheckItem())){
                errors.add(String.format("第{%s}行:检查项目不能为空",itemBean.getRowIndex()));
                error++;
                continue;
            }*//*else if (StringUtils.isBlank(itemBean.getCheckStandard())){
                errors.add(String.format("第{%s}行:检查标准不能为空",itemBean.getRowIndex()));
                error++;
                continue;
            }*//*else if (StringUtils.isBlank(itemBean.getPhotograph())){
                errors.add(String.format("第{%s}行:是否强制拍照不能为空",itemBean.getRowIndex()));
                error++;
                continue;
            }else if (checkRecord(itemBean)){
                errors.add(String.format("第{%s}行:数值,状态,文本都为空",itemBean.getRowIndex()));
                error++;
                continue;
            }
            //检查项目
            checkItemDetailVo.setCheckItem(itemBean.getCheckItem());
            //检查标准
            checkItemDetailVo.setCheckStandard(itemBean.getCheckStandard());

            try {
                BpDeviceFacilityCollection deviceFacilityCollection = bpDeviceFacilityCollectionDao.findFirstByCode(itemBean.getDeviceCode());
                if (null == deviceFacilityCollection){
                    errors.add(String.format("第{%s}行:设备编号不存在",itemBean.getRowIndex()));
                    error++;
                    continue;
                }else {
                    checkItemDetailVo.setDeviceId(deviceFacilityCollection.getId());
                }
                if (!("是".equals(itemBean.getPhotograph()) || "否".equals(itemBean.getPhotograph()))){
                    errors.add(String.format("第{%s}行:强制拍照字段请在{是,否}中选择",itemBean.getRowIndex()));
                    error++;
                    continue;
                }else {
                    String photograph = itemBean.getPhotograph().equals("是") ? "1" : "0";
                    checkItemDetailVo.setPhotograph(photograph);
                }
                //状态,数值,文本,同时存在取状态
                if (StringUtils.isNotBlank(itemBean.getStateDataName())){
                    //保存状态数据名称

                }else if (StringUtils.isBlank(itemBean.getStateDataName()) && StringUtils.isNotBlank(itemBean.getNumDataType())){
                    //为数值状态时     例: 温度(℃)   连锁投切
                    String numDataType = itemBean.getNumDataType();
                    //第一种情况需要按照名称和单位查找
                    if (numDataType.contains("(") && numDataType.contains(")")){

                    }else {
                        //第二种情况需要按照名称搜索
                    }
                    List<String> symbolList = getSymbolList();
                    if (StringUtils.isNotBlank(itemBean.getSymbol())){
                        //如果输入的字符不包含在list中
                        if (!symbolList.contains(itemBean.getSymbol())){
                            errors.add(String.format("第{%s}行:在规定的逻辑符号中选择",itemBean.getRowIndex()));
                            error++;
                            continue;
                        }
                    }else {
                        errors.add(String.format("第{%s}行:必须选择一个逻辑符号",itemBean.getRowIndex()));
                        error++;
                        continue;
                    }

                }else if (StringUtils.isBlank(itemBean.getStateDataName()) && StringUtils.isBlank(itemBean.getNumDataType()) && StringUtils.isNotBlank(itemBean.getText())){
                    //选择的是文本 则将数据类型设置为文本
                    checkItemDetailVo.setDataType(DataTypeEnum.TEXT.getValue());
                }

                checkItemDetailVoList.add(checkItemDetailVo);
                count ++;

            }catch (Exception e){
                errors.add(String.format("第{%s}行,数据错误",itemBean.getRowIndex()));
                error ++;
                log.error(e.getMessage(),e);
            }
        }
        checkItemBean.setCount(count);
        checkItemBean.setError(error);
        checkItemBean.setErrors(errors);
        if (CollectionUtil.isNotEmpty(checkItemDetailVoList)){
            List<CheckItemVo> checkItemVoList = convertForExcel(checkItemDetailVoList);
            checkItemBean.setCheckItemVoList(checkItemVoList);
        }
        return checkItemBean;
    }*/

    @Override
    public CheckItemBean importCheckItem(MultipartFile file, List<PatrolCheckPointItemDetailBean> frontEndData, Integer flag) {
        XSSFWorkbook workbook = null;
        CheckItemBean checkItemBean = new CheckItemBean();
        if (!file.getOriginalFilename().endsWith(".xlsx")) {
            throw new IllegalArgumentException("请使用xlsx文件导入");
        }
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null == workbook) {
            throw new IllegalArgumentException("sheet(1)无法解析到数据");
        }
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        if (null != sheetAt) {
            List<ExcelCheckItemBean> sheetData = getSheetData(sheetAt);
            checkItemBean = parseData(sheetData, frontEndData, flag);
        }
        return checkItemBean;
    }

    /**
     * 处理数据
     *
     * @return
     */
    private CheckItemBean parseData(List<ExcelCheckItemBean> itemBeanList, List<PatrolCheckPointItemDetailBean> frontEndData, Integer flag) {
        CheckItemBean checkItemBean = new CheckItemBean();
        int error = 0;
        int count = 0;
        List<String> errors = new ArrayList<>();
        List<CheckItemDetailVo> checkItemDetailVoList = new ArrayList<>();
        Map<String, Long> checkCodeMap = Maps.newHashMap();
        Map<Long, String> tempCheckObjIdNameMap = Maps.newHashMap();
        if (CollectionUtil.isNotEmpty(itemBeanList)) {
            for (ExcelCheckItemBean itemBean : itemBeanList) {
                if (StringUtils.isNotEmpty(itemBean.getDefCheckObj())) {
                    if (itemBean.getDefCheckObj().length() > 64) {
                        errors.add(String.format("第{%s}行,自定检查对象长度不能超过64", itemBean.getRowIndex()));
                        error++;
                        continue;
                    }
                } else {
                    if (StringUtils.isBlank(itemBean.getDeviceCode())) {
                        errors.add(String.format("第{%s}行,设备编号不能为空", itemBean.getRowIndex()));
                        error++;
                        continue;
                    }
                }
                if (StringUtils.isBlank(itemBean.getCheckItem())) {
                    errors.add(String.format("第{%s}行,检查项目不能为空", itemBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (StringUtils.isBlank(itemBean.getCheckStandard())) {
                    errors.add(String.format("第{%s}行,检查标准不能为空", itemBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (StringUtils.isBlank(itemBean.getPhotograph())) {
                    errors.add(String.format("第{%s}行,是否强制拍照不能为空", itemBean.getRowIndex()));
                    error++;
                    continue;
                }
                if (StringUtils.isBlank(itemBean.getStateDataName()) && StringUtils.isBlank(itemBean.getShockDataType()) && StringUtils.isBlank(itemBean.getNumDataType()) && StringUtils.isBlank(itemBean.getText())) {
                    errors.add(String.format("第{%s}行,状态数据名称,数值数据名称,文本,温振仪类型不能同时为空", itemBean.getRowIndex()));
                    error++;
                    continue;
                }

                //将数据赋值给前端需要的格式
                CheckItemVo vo = new CheckItemVo();
                //检查项目细节,先全部赋值,最后通过设备id分组,返回给前端

                CheckItemDetailVo detailVo = new CheckItemDetailVo();
                detailVo.setDefCheckObj(itemBean.getDefCheckObj());
                //设备编号
                String code = itemBean.getDeviceCode();
                if (riskEvaluationExcelImportService.isNum(code)) {
                    code = riskEvaluationExcelImportService.getNumberString(code);
                    detailVo.setDeviceCode(code);
                }

                if (StringUtils.isEmpty(itemBean.getDefCheckObj())) {
                    BpDeviceFacilityCollection deviceFacilityCollection = bpDeviceFacilityCollectionDao.findByCodeAndTypeName(code, itemBean.getDeviceTypeName());
                    if (null == deviceFacilityCollection) {
                        errors.add(String.format("第{%s}行:设备编号不存在", itemBean.getRowIndex()));
                        error++;
                        continue;
                    } else {
                        detailVo.setDeviceId(deviceFacilityCollection.getId());
                    }
                    //设备类型
                    detailVo.setDeviceTypeName(deviceFacilityCollection.getDeviceTypeName());
                } else {
                    Long tempDeviceId = checkCodeMap.get(itemBean.getDefCheckObj());
                    if (tempDeviceId == null) {
                        if (frontEndData != null) {
                            for (PatrolCheckPointItemDetailBean fontBean : frontEndData) {
                                if (StringUtils.isNotEmpty(fontBean.getDeviceName()) && fontBean.getDeviceName().equals(itemBean.getDefCheckObj())) {
                                    tempDeviceId = fontBean.getDeviceId();
                                }
                            }
                        }
                        if (tempDeviceId == null) {
                            tempDeviceId = 0 - System.currentTimeMillis();
                        }
                        checkCodeMap.put(itemBean.getDefCheckObj(), tempDeviceId);
                    }
                    tempCheckObjIdNameMap.put(tempDeviceId, itemBean.getDefCheckObj());
                    detailVo.setDeviceId(tempDeviceId);
                }
                //检查项目
                String strCheckItem = "";
                strCheckItem = getStrValue(itemBean.getCheckItem());
                detailVo.setCheckItem(strCheckItem);
                //检查标准
                String strCheckStandard = "";
                strCheckStandard = getStrValue(itemBean.getCheckStandard());
                detailVo.setCheckStandard(strCheckStandard);
                //是否强制拍照
                if (!("是".equals(itemBean.getPhotograph()) || "否".equals(itemBean.getPhotograph()))) {
                    errors.add(String.format("第{%s}行:强制拍照字段请在{是,否}中选择", itemBean.getRowIndex()));
                    error++;
                    continue;
                } else {
                    String photograph = itemBean.getPhotograph().equals("是") ? "1" : "0";
                    detailVo.setPhotograph(photograph);
                }
                //状态,数值,文本
                if (StringUtils.isNotBlank(itemBean.getStateDataName())) {
                    detailVo.setDataType(DataTypeEnum.STATE.getValue());
                    //保存状态数据名称
                    //查找数据状态名称是否存在
                    String dataName = itemBean.getStateDataName();
                    if (riskEvaluationExcelImportService.isNum(dataName)) {
                        dataName = riskEvaluationExcelImportService.getNumberString(dataName);
                        detailVo.setNormalValueName(dataName);
                    }
                    PatrolDataType dataType = patrolDataTypeMapper.findByName(dataName, Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                    if (null == dataType) {
                        errors.add(String.format("第{%s}行:状态数据名称不存在", itemBean.getRowIndex()));
                        error++;
                        continue;
                    } else {
                        detailVo.setDataTypeId(dataType.getId());
                        detailVo.setDataTypeName(dataType.getDataName());
                        //正常值(单选时确认正常值,多选时无需确认)
                        if (Constant.COMMON_SWITCH_OFF.equals(dataType.getSingletonChoiceFlag())) {
                            detailVo.setSingletonChoiceFlag(Constant.COMMON_SWITCH_OFF);
                            //单选时正常值不能为空
                            if (StringUtils.isBlank(itemBean.getNormalValueName())) {
                                errors.add(String.format("第{%s}行:状态数据为单选,正常值不能为空", itemBean.getRowIndex()));
                                error++;
                                continue;
                            } else {
                                //判断该状态数据下的正常值选项是否存在
                                PatrolOption option = patrolOptionMapper.findByTypeIdAndName(dataType.getId(), itemBean.getNormalValueName(), Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                                if (null == option) {
                                    errors.add(String.format("第{%s}行:该状态数据下的正常值不存在", itemBean.getRowIndex()));
                                    error++;
                                    continue;
                                } else {
                                    detailVo.setNormalValueId(option.getId());
                                    detailVo.setNormalValueName(option.getOptionUnit());
                                }
                            }
                        } else if (Constant.COMMON_SWITCH_ON.equals(dataType.getSingletonChoiceFlag())) {
                            detailVo.setSingletonChoiceFlag(Constant.COMMON_SWITCH_ON);
                        }
                    }
                    //数值状态
                } else if (StringUtils.isBlank(itemBean.getStateDataName()) && StringUtils.isNotBlank(itemBean.getNumDataType())) {
                    detailVo.setDataType(DataTypeEnum.NUM.getValue());
                    //为数值状态时     例: 温度(℃)   连锁投切
                    String numDataType = itemBean.getNumDataType();
                    //查看数值数据名称是否存在
                    List<SimpleListDataType> simpleListDataType = patrolCheckPointService.getSimpleListDataType(DataTypeEnum.NUM.getValue());
                    if (CollectionUtil.isEmpty(simpleListDataType)) {
                        errors.add(String.format("第{%s}行:数值数据名称不存在", itemBean.getRowIndex()));
                        error++;
                        continue;
                    } else {
                        List<String> numDataNameList = simpleListDataType.stream().map(SimpleListDataType::getDataTypeName).collect(toList());
                        if (!numDataNameList.contains(numDataType)) {
                            errors.add(String.format("第{%s}行:数值数据名称不存在", itemBean.getRowIndex()));
                            error++;
                            continue;
                        } else {
                            detailVo.setDataTypeName(numDataType);
                            Long dataTypeId = null;
                            for (SimpleListDataType dataType : simpleListDataType) {
                                if (numDataType.equals(dataType.getDataTypeName())) {
                                    dataTypeId = dataType.getId();
                                    break;
                                }
                            }
                            detailVo.setDataTypeId(dataTypeId);
                        }
                    }

                    //判断符号
                    List<String> symbolList = getSymbolList();
                    if (StringUtils.isNotBlank(itemBean.getSymbol())) {
                        //如果输入的字符不包含在list中
                        if (!symbolList.contains(itemBean.getSymbol())) {
                            errors.add(String.format("第{%s}行:在规定的逻辑符号中选择", itemBean.getRowIndex()));
                            error++;
                            continue;
                        }
                        detailVo.setSymbol(itemBean.getSymbol());
                        //根据选择的符号判断需要填写一个区间值还是两个
                        if (judgeSymbol(itemBean.getSymbol())) {
                            //需要两个区间都填写
                            if (StringUtils.isBlank(itemBean.getNormalValueLeft()) || StringUtils.isBlank(itemBean.getNormalValueRight())) {
                                errors.add(String.format("第{%s}行:正常值区间1,2必须填写", itemBean.getRowIndex()));
                                error++;
                                continue;
                            } else {
                                //判断值是否是数值
                                try {
                                    if (itemBean.getNormalValueLeft().contains(".")) {
                                        Double left = Double.parseDouble(itemBean.getNormalValueLeft());
                                        String leftStr = "";
                                        String rightStr = "";
                                        leftStr = getStrValue(left);
                                        if (itemBean.getNormalValueRight().contains(".")) {
                                            Double right = Double.parseDouble(itemBean.getNormalValueRight());
                                            rightStr = getStrValue(right);
                                            //按数值大小交换位置
                                            if (left > right) {
                                                detailVo.setNormalLeft(rightStr);
                                                detailVo.setNormalRight(leftStr);

                                            } else {
                                                detailVo.setNormalLeft(leftStr);
                                                detailVo.setNormalRight(rightStr);
                                            }
                                        } else {
                                            Long right1 = Long.parseLong(itemBean.getNormalValueRight());
                                            rightStr = getStrValue(right1);
                                            if (left > right1) {
                                                detailVo.setNormalLeft(rightStr);
                                                detailVo.setNormalRight(leftStr);
                                            } else {
                                                detailVo.setNormalLeft(leftStr);
                                                detailVo.setNormalRight(rightStr);
                                            }
                                        }
                                    } else {
                                        Long left = Long.parseLong(itemBean.getNormalValueLeft());
                                        String leftStr = "";
                                        String rightStr = "";
                                        leftStr = getStrValue(left);
                                        if (itemBean.getNormalValueRight().contains(".")) {
                                            Double right = Double.parseDouble(itemBean.getNormalValueRight());
                                            rightStr = getStrValue(right);
                                            //按数值大小交换位置
                                            if (left > right) {
                                                detailVo.setNormalLeft(rightStr);
                                                detailVo.setNormalRight(leftStr);
                                            } else {
                                                detailVo.setNormalLeft(leftStr);
                                                detailVo.setNormalRight(rightStr);
                                            }
                                        } else {
                                            Long right1 = Long.parseLong(itemBean.getNormalValueRight());
                                            rightStr = getStrValue(right1);
                                            if (left > right1) {
                                                detailVo.setNormalLeft(rightStr);
                                                detailVo.setNormalRight(leftStr);
                                            } else {
                                                detailVo.setNormalLeft(leftStr);
                                                detailVo.setNormalRight(rightStr);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    errors.add(String.format("第{%s}行:正常值区间为数字类型", itemBean.getRowIndex()));
                                    error++;
                                    continue;
                                }
                            }
                            //一个区间填写,默认取第一个区间值
                        } else {
                            if (StringUtils.isBlank(itemBean.getNormalValueLeft())) {
                                errors.add(String.format("第{%s}行:正常值区间1必须填写", itemBean.getRowIndex()));
                                error++;
                                continue;
                            } else {
                                String leftStr = "";
                                leftStr = getStrValue(itemBean.getNormalValueLeft());
                                detailVo.setNormalLeft(leftStr);
                            }
                        }
                    } else {
                        errors.add(String.format("第{%s}行:必须选择一个逻辑符号", itemBean.getRowIndex()));
                        error++;
                        continue;
                    }

                } else if (StringUtils.isBlank(itemBean.getStateDataName()) && StringUtils.isBlank(itemBean.getNumDataType()) && StringUtils.isNotBlank(itemBean.getText())) {
                    //选择的是文本 则将数据类型设置为文本
                    detailVo.setDataType(DataTypeEnum.TEXT.getValue());
                } else if (StringUtils.isBlank(itemBean.getStateDataName()) && StringUtils.isBlank(itemBean.getNumDataType()) && StringUtils.isNotBlank(itemBean.getShockDataType()) && StringUtils.isBlank(itemBean.getText())) {
                    detailVo.setDataType(DataTypeEnum.SHOCK.getValue());
                    //为数值状态时     例: 温度(℃)   连锁投切
                    String shockDataType = itemBean.getShockDataType();
                    //查看数值数据名称是否存在
                    List<SimpleListDataType> simpleListDataType = patrolCheckPointService.getSimpleListDataType(DataTypeEnum.SHOCK.getValue());
                    if (CollectionUtil.isEmpty(simpleListDataType)) {
                        errors.add(String.format("第{%s}行:温振仪数据名称不存在", itemBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    List<String> ShockDataNameList = simpleListDataType.stream().map(SimpleListDataType::getDataTypeName).collect(toList());
                    if (!ShockDataNameList.contains(shockDataType)) {
                        errors.add(String.format("第{%s}行:温振仪数据名称不存在", itemBean.getRowIndex()));
                        error++;
                        continue;
                    }
                    detailVo.setDataTypeName(shockDataType);
                    Long dataTypeId = null;
                    for (SimpleListDataType dataType : simpleListDataType) {
                        if (shockDataType.equals(dataType.getDataTypeName())) {
                            dataTypeId = dataType.getId();
                            break;
                        }
                    }
                    detailVo.setDataTypeId(dataTypeId);

                    //判断符号
                    List<String> symbolList = getSymbolList();
                    if (StringUtils.isNotBlank(itemBean.getSymbolShock())) {
                        //如果输入的字符不包含在list中
                        if (!symbolList.contains(itemBean.getSymbolShock())) {
                            errors.add(String.format("第{%s}行:在规定的逻辑符号中选择", itemBean.getRowIndex()));
                            error++;
                            continue;
                        }
                        detailVo.setSymbol(itemBean.getSymbolShock());
                        //根据选择的符号判断需要填写一个区间值还是两个
                        if (judgeSymbol(itemBean.getSymbolShock())) {
                            //需要两个区间都填写
                            if (StringUtils.isBlank(itemBean.getNormalValueLeftShock()) || StringUtils.isBlank(itemBean.getNormalValueRightShock())) {
                                errors.add(String.format("第{%s}行:正常值区间1,2必须填写", itemBean.getRowIndex()));
                                error++;
                                continue;
                            }
                            //判断值是否是数值
                            try {
                                if (itemBean.getNormalValueLeftShock().contains(".")) {
                                    Double left = Double.parseDouble(itemBean.getNormalValueLeftShock());
                                    String leftStr = "";
                                    String rightStr = "";
                                    leftStr = getStrValue(left);
                                    if (itemBean.getNormalValueRightShock().contains(".")) {
                                        Double right = Double.parseDouble(itemBean.getNormalValueRightShock());
                                        rightStr = getStrValue(right);
                                        //按数值大小交换位置
                                        if (left > right) {
                                            detailVo.setNormalLeft(rightStr);
                                            detailVo.setNormalRight(leftStr);

                                        } else {
                                            detailVo.setNormalLeft(leftStr);
                                            detailVo.setNormalRight(rightStr);
                                        }
                                    } else {
                                        Long right1 = Long.parseLong(itemBean.getNormalValueRightShock());
                                        rightStr = getStrValue(right1);
                                        if (left > right1) {
                                            detailVo.setNormalLeft(rightStr);
                                            detailVo.setNormalRight(leftStr);
                                        } else {
                                            detailVo.setNormalLeft(leftStr);
                                            detailVo.setNormalRight(rightStr);
                                        }
                                    }
                                } else {
                                    Long left = Long.parseLong(itemBean.getNormalValueLeftShock());
                                    String leftStr = "";
                                    String rightStr = "";
                                    leftStr = getStrValue(left);
                                    if (itemBean.getNormalValueRightShock().contains(".")) {
                                        Double right = Double.parseDouble(itemBean.getNormalValueRightShock());
                                        rightStr = getStrValue(right);
                                        //按数值大小交换位置
                                        if (left > right) {
                                            detailVo.setNormalLeft(rightStr);
                                            detailVo.setNormalRight(leftStr);
                                        } else {
                                            detailVo.setNormalLeft(leftStr);
                                            detailVo.setNormalRight(rightStr);
                                        }
                                    } else {
                                        Long right1 = Long.parseLong(itemBean.getNormalValueRightShock());
                                        rightStr = getStrValue(right1);
                                        if (left > right1) {
                                            detailVo.setNormalLeft(rightStr);
                                            detailVo.setNormalRight(leftStr);
                                        } else {
                                            detailVo.setNormalLeft(leftStr);
                                            detailVo.setNormalRight(rightStr);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                errors.add(String.format("第{%s}行:正常值区间为数字类型", itemBean.getRowIndex()));
                                error++;
                                continue;
                            }

                            //一个区间填写,默认取第一个区间值
                        } else {
                            if (StringUtils.isBlank(itemBean.getNormalValueLeftShock())) {
                                errors.add(String.format("第{%s}行:正常值区间1必须填写", itemBean.getRowIndex()));
                                error++;
                                continue;
                            } else {
                                String leftStr = "";
                                leftStr = getStrValue(itemBean.getNormalValueLeftShock());
                                detailVo.setNormalLeft(leftStr);
                            }
                        }
                    } else {
                        if (!itemBean.getShockDataType().equals("振动")) {
                            errors.add(String.format("第{%s}行:必须选择一个逻辑符号", itemBean.getRowIndex()));
                            error++;
                            continue;
                        }

                    }

                }
                count++;
                checkItemDetailVoList.add(detailVo);
            }
        }
        //讲模板数据与已有的数据进行合并或者覆盖
        checkItemBean = dealWith(checkItemDetailVoList, frontEndData, flag, tempCheckObjIdNameMap);
        checkItemBean.setErrors(errors);
        checkItemBean.setCount(count);
        checkItemBean.setError(error);
        return checkItemBean;
    }

    private String getStrValue(Object d) {
        String str = "";
        if (d == null) {
            return str;
        }
        if (riskEvaluationExcelImportService.isNum(d.toString())) {
            str = riskEvaluationExcelImportService.getNumberString(d.toString());
        } else {
            str = d.toString();
        }
        return str;
    }

    /**
     * 将同设备id的数据合并返回给前端
     *
     * @param templateData 模板数据
     * @param frontEndData 前端数据
     * @return
     */
    private CheckItemBean dealWith(List<CheckItemDetailVo> templateData, List<PatrolCheckPointItemDetailBean> frontEndData,
                                   Integer flag, Map<Long, String> tempCheckObjIdNameMap) {

        CheckItemBean checkItemBean = new CheckItemBean();
        List<Long> deviceIdList = new ArrayList<>();
        List<CheckItemVo> checkItemVoList = new ArrayList<>();

        //根据是flag判断是追加还是覆盖  0:追加   在前端传入的数据上将模板中的数据追加进去
        //                             1:覆盖   将前端传入的带有id的数据放入删除ids集合中同模板数据返回给前端

        List<CheckItemDetailVo> resultData = additionData(templateData, frontEndData, flag); // 模板和前端数据的最终
        //覆盖并且是前端数据不为空,则将前端的检查项目id给前端,修改保存时进行删除操作
        /*if ( 1 == flag && CollectionUtil.isNotEmpty(frontEndData)){
            List<Long> delIds = frontEndData.stream().map(PatrolCheckPointItemDetailBean::getId).filter(Objects::nonNull).collect(Collectors.toList());
            checkItemBean.setDelItemIds(delIds);
        }*/
        List<Long> templateIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(resultData)) {
//            templateIdList = templateData.stream().filter(e -> e.getDeviceId() != null).map(CheckItemDetailVo::getDeviceId).distinct().collect(Collectors.toList());
            templateIdList = templateData.stream().map(CheckItemDetailVo::getDeviceId).distinct().collect(Collectors.toList());
        }
        if (flag == 0) {
            if (!CollectionUtils.isEmpty(frontEndData)) {
//                deviceIdList = frontEndData.stream().filter(e -> e.getDeviceId() != null).map(PatrolCheckPointItemDetailBean::getDeviceId).distinct().collect(Collectors.toList());
                deviceIdList = frontEndData.stream().map(PatrolCheckPointItemDetailBean::getDeviceId).distinct().collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(templateIdList)) {
                for (Long id : templateIdList) {
                    if (!deviceIdList.contains(id)) {
                        deviceIdList.add(id);
                    }
                }
            }
        } else if (flag == 1) {
            deviceIdList = templateIdList;
        }
//        resultData.stream()
//                .filter(e -> e.getDeviceId() == null)
//                .collect(toList())
//                .forEach(e -> {
//                    CheckItemVo checkItemVo = new CheckItemVo();
//                    checkItemVo.setDeviceName(e.getDefCheckObj());
//                    checkItemVo.setDeviceCode("-");
//                    List<CheckItemDetailVo> detailVoList = new ArrayList<>();
//                    detailVoList.add(e);
//                    checkItemVo.setCheckItemDetailVoList(detailVoList);
//                    checkItemVoList.add(checkItemVo);
//                });

        if (CollectionUtil.isNotEmpty(deviceIdList)) {
            for (Long deviceId : deviceIdList) {
                CheckItemVo checkItemVo = new CheckItemVo();
                List<CheckItemDetailVo> detailVoList = new ArrayList<>();
                if (deviceId > 0) {
                    Optional<BpDeviceFacilityCollection> optional = bpDeviceFacilityCollectionDao.findById(deviceId);
                    if (optional != null && optional.isPresent()) {
                        BpDeviceFacilityCollection device = optional.get();
                        checkItemVo.setDeviceId(deviceId);
                        checkItemVo.setDeviceName(device.getName());
                        checkItemVo.setDeviceCode(device.getCode());
                    }
                } else {
                    checkItemVo.setDeviceId(deviceId);
                    checkItemVo.setDeviceName(tempCheckObjIdNameMap.get(deviceId));
                }
                for (CheckItemDetailVo checkItemDetailVo : resultData) {
                    if (deviceId.equals(checkItemDetailVo.getDeviceId())) {
                        detailVoList.add(checkItemDetailVo);
                    }
                }
                checkItemVo.setCheckItemDetailVoList(detailVoList);
                checkItemVoList.add(checkItemVo);
            }
        }

        checkItemBean.setCheckItemVoList(checkItemVoList);

        return checkItemBean;
    }


    /**
     * 将前端传入的数据和模板解析的数据进行合并
     *
     * @param checkItemDetailVoList 模板数据
     * @param frontEndData          前端数据
     * @return
     */
    private List<CheckItemDetailVo> additionData(List<CheckItemDetailVo> checkItemDetailVoList, List<PatrolCheckPointItemDetailBean> frontEndData, Integer flag) {
        //先将前端数据转为后面需要给前端的类型
        List<CheckItemDetailVo> returnData = new ArrayList<>();
        List<CheckItemDetailVo> convertData = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(frontEndData)) {
            for (PatrolCheckPointItemDetailBean bean : frontEndData) {
                CheckItemDetailVo detailVo = new CheckItemDetailVo();
                detailVo.setId(bean.getId());
                detailVo.setDeviceId(bean.getDeviceId());
                detailVo.setCheckItem(bean.getCheckItem());
                detailVo.setCheckStandard(bean.getCheckStandard());
                detailVo.setDataType(bean.getDataType());
                detailVo.setDataTypeId(bean.getDataTypeId());
                detailVo.setDataTypeName(bean.getDataTypeName());
                detailVo.setSingletonChoiceFlag(bean.getSingletonChoiceFlag());
                detailVo.setSymbol(bean.getSymbol());
                detailVo.setNormalLeft(bean.getNormalLeft());
                detailVo.setNormalRight(bean.getNormalRight());
                detailVo.setNormalValueId(bean.getNormalValueId());
                detailVo.setNormalValueName(bean.getNormalValueName());
                detailVo.setPhotograph(bean.getPhotograph());
                convertData.add(detailVo);
            }
        }
        // 1: 覆盖   0: 追加
        if (1 == flag) {
            returnData = checkItemDetailVoList;
        } else if (0 == flag) {
            returnData = convertData;
            returnData.addAll(checkItemDetailVoList);
        }
        return returnData;
    }

    /**
     * 获取检查项目excel的数据
     *
     * @param sheet
     * @return
     */
    private List<ExcelCheckItemBean> getSheetData(XSSFSheet sheet) {
        XSSFRow row;
        List<ExcelCheckItemBean> itemBeanList = new ArrayList<>();
        for (int i = 2; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            ExcelCheckItemBean item = new ExcelCheckItemBean();
            //取每一行的值
            item.setRowIndex(i + 1);
            //设备编号
            XSSFCell cell = row.getCell(0);

            if (null != cell) {
                item.setDeviceCode(getCellStringValue(cell));
            }
            //设备类型
            XSSFCell cell1 = row.getCell(1);
            if (null != cell1) {
                item.setDeviceTypeName(getCellStringValue(cell1));
            }
            XSSFCell cell222 = row.getCell(2);
            if (null != cell222) {
                item.setDefCheckObj(getCellStringValue(cell222));
            }
            //检查项目
            XSSFCell cell2 = row.getCell(3);
            if (null != cell2) {
                item.setCheckItem(getCellStringValue(cell2));
            }
            //检查标准
            XSSFCell cell3 = row.getCell(4);
            if (null != cell3) {
                item.setCheckStandard(getCellStringValue(cell3));
            }
            //如果设备编号,检查项目,检查标准同时为空,则默认此为最后一行,不在往下解析数据
            if (StringUtils.isBlank(item.getDeviceCode()) && StringUtils.isBlank(item.getCheckItem()) && StringUtils.isBlank(item.getCheckStandard())) {
                break;
            }

            //是否强制拍照
            XSSFCell cell4 = row.getCell(5);
            if (null != cell4) {
                item.setPhotograph(getCellStringValue(cell4));
            }
            //状态数据名称
            XSSFCell cell5 = row.getCell(6);
            if (null != cell5) {
                item.setStateDataName(getCellStringValue(cell5));
            }
            //正常值
            XSSFCell cell6 = row.getCell(7);
            if (null != cell6) {
                item.setNormalValueName(getCellStringValue(cell6));
            }
            //数值数据名称
            XSSFCell cell7 = row.getCell(8);
            if (null != cell7) {
                item.setNumDataType(getCellStringValue(cell7));
            }
            //数据计算逻辑
            XSSFCell cell8 = row.getCell(9);
            if (null != cell8) {
                item.setSymbol(getCellStringValue(cell8));
            }
            //正常值下限
            XSSFCell cell9 = row.getCell(10);
            if (null != cell9) {
                item.setNormalValueLeft(getCellStringValue(cell9));
            }
            //正常值上限
            XSSFCell cell10 = row.getCell(11);
            if (null != cell10) {
                item.setNormalValueRight(getCellStringValue(cell10));
            }
            //文本
            XSSFCell cell11 = row.getCell(12);
            if (null != cell11) {
                item.setText(getCellStringValue(cell11));
            }
            //温振仪
            XSSFCell cell12 = row.getCell(13);
            if (null != cell12) {
                item.setShockDataType(getCellStringValue(cell12));
            }
            //数据计算逻辑
            XSSFCell cell13 = row.getCell(14);
            if (null != cell13) {
                item.setSymbolShock(getCellStringValue(cell13));
            }
            //正常值下限
            XSSFCell cell14 = row.getCell(15);
            if (null != cell14) {
                item.setNormalValueLeftShock(getCellStringValue(cell14));
            }
            //正常值上限
            XSSFCell cell15 = row.getCell(16);
            if (null != cell15) {
                item.setNormalValueRightShock(getCellStringValue(cell15));
            }
            itemBeanList.add(item);
        }
        return itemBeanList;
    }


    public String getCellStringValue(XSSFCell cell) {
        Object obj = getCellValue(cell, true);
        return obj == null ? null : obj.toString().trim();
    }

    private Object getCellValue(XSSFCell cell, boolean isText) {
        CellType cellType = cell.getCellType();
        DecimalFormat df = new DecimalFormat("0");
        Object value = null;
        switch (cellType) {
            case STRING: {
                value = cell.getStringCellValue();
                break;
            }
            case NUMERIC: {
                value = cell.getNumericCellValue();
                if (isText) {
                    BigDecimal decimal = new BigDecimal(value.toString());
                    int scale = decimal.scale();
                    if (scale < 1) {
                        //小于1代表科学计数或者整数
                        value = df.format(decimal);
                    } else {
                        value = String.valueOf(decimal);
                    }
                    return String.valueOf(value);
                }
                break;
            }
            case FORMULA: {
                value = cell.getNumericCellValue();
                if (isText) {
                    return value.toString();
                }
                break;
            }
        }
        return value;
    }

    /**
     * 检查数值,状态,文本是否都是空
     *
     * @param itemBean
     * @return
     */
    private boolean checkRecord(ExcelCheckItemBean itemBean) {
        boolean flag = false;
        String stateDataName = itemBean.getStateDataName();
        String numDataType = itemBean.getNumDataType();
        String text = itemBean.getText();
        if (StringUtils.isBlank(stateDataName) && StringUtils.isBlank(numDataType) && StringUtils.isBlank(text)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取符号集合
     *
     * @return
     */
    public List<String> getSymbolList() {
        List<String> result = new ArrayList<>();
        result.add(">");
        result.add("≥");
        result.add("<");
        result.add("≤");
        result.add("><");
        result.add("≥≤");
        return result;
    }

    /**
     * 根据符号判断属于那种类型
     * true : >< , ≥≤   需要两个区间值
     * false : > , ≥ , < , ≤ 只需一个区间值
     *
     * @param symbol
     * @return
     */
    private boolean judgeSymbol(String symbol) {
        if ("><".equals(symbol) || "≥≤".equals(symbol)) {
            return true;
        } else if (">".equals(symbol) || "≥".equals(symbol) || "<".equals(symbol) || "≤".equals(symbol)) {
            return false;
        }
        return false;
    }

    /**
     * 将同一个设备下的数据做出区分
     *
     * @param checkItemDetailVoList
     * @return
     */
    private List<CheckItemVo> convertForExcel(List<CheckItemDetailVo> checkItemDetailVoList) {
        List<CheckItemVo> result = new ArrayList<>();
        Set<Long> deviceIds = checkItemDetailVoList.stream().map(CheckItemDetailVo::getDeviceId).collect(Collectors.toSet());
        for (Long deviceId : deviceIds) {
            CheckItemVo checkItemVo = new CheckItemVo();
            checkItemVo.setDeviceId(deviceId);
            BpDeviceFacilityCollection facilityCollection = bpDeviceFacilityCollectionDao.findFirstByDeviceId(deviceId);
            if (null != facilityCollection) {
                checkItemVo.setDeviceCode(facilityCollection.getCode());
                checkItemVo.setDeviceName(facilityCollection.getName());
            }
            List<CheckItemDetailVo> checkItemDetailVos = checkItemDetailVoList.stream().filter(e -> e.getDeviceId().equals(deviceId)).collect(toList());
            checkItemVo.setCheckItemDetailVoList(checkItemDetailVos);
            result.add(checkItemVo);
        }
        return result;
    }

    @Override
    public List<String> importIMEIByExcel(MultipartFile file) {
        List<ExcelIMEIBean> beans = parseData(file, 0, ExcelIMEIBean.class, true);
        List<String> errors = new ArrayList<>();
        int count = 0;
        int error = 0;
        int ignore = 0;
        String regex = "[0-9a-zA-Z_-]{1,64}";
        for (int i = 0; i < beans.size(); i++) {
            ExcelIMEIBean bean = beans.get(i);
            if (bean.getCode() != null) {
                bean.setCode(bean.getCode().trim());
            }
            if (bean.getImei() != null) {
                bean.setImei(bean.getImei().trim());
            }
            if (StringUtils.isBlank(bean.getCode())) {
                errors.add(String.format("IMEI第{%s}行:人员工号不能为空", bean.getRowIndex()));
                error++;
                continue;
            } else if (StringUtils.isBlank(bean.getImei())) {
                errors.add(String.format("IMEI第{%s}行:IMEI不能为空", bean.getRowIndex()));
                error++;
                continue;
            }
            if (!bean.getImei().matches(regex)){
                errors.add(String.format("IMEI第{%s}行:IMEI格式不正确,IMEI为64位内大小写字母或数字或-或_组成", bean.getRowIndex()));
                error++;
                continue;
            }
            BaseUser user = baseUserDao.findByCode(bean.getCode());
            if (user == null){
                errors.add(String.format("IMEI第{%s}行:人员不存在", bean.getRowIndex()));
                error++;
                continue;
            }
            user.setImei(bean.getImei());
            try {
                baseUserDao.save(user);
                count++;
            } catch (Exception e) {
                log.error("IMEI第" + bean.getRowIndex() + "添加失败", e);
                errors.add(String.format("IMEI第{%s}行:添加失败", bean.getRowIndex()));
                error++;
            }
        }
        return returnList(errors, count, error, ignore, "IMEI");
    }
}
